org.el 954 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219
  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-mode 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 contain
  29. ;; information about projects as plain text. Org-mode is implemented on
  30. ;; top of outline-mode, which makes it possible to keep the content of
  31. ;; large files well structured. Visibility cycling and structure editing
  32. ;; help to work with the tree. Tables are easily created with a built-in
  33. ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
  34. ;; and scheduling. It dynamically compiles entries into an agenda that
  35. ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
  36. ;; Plain text URL-like links connect to websites, emails, Usenet
  37. ;; messages, BBDB entries, and any files related to the projects. For
  38. ;; printing and sharing of notes, an Org-mode file can be exported as a
  39. ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
  40. ;; iCalendar file. It can also serve as a publishing tool for a set of
  41. ;; linked webpages.
  42. ;;
  43. ;; Installation and Activation
  44. ;; ---------------------------
  45. ;; See the corresponding sections in the manual at
  46. ;;
  47. ;; http://orgmode.org/org.html#Installation
  48. ;;
  49. ;; Documentation
  50. ;; -------------
  51. ;; The documentation of Org-mode can be found in the TeXInfo file. The
  52. ;; distribution also contains a PDF version of it. At the homepage of
  53. ;; Org-mode, you can read the same text online as HTML. There is also an
  54. ;; excellent reference card made by Philip Rooke. This card can be found
  55. ;; in the etc/ directory of Emacs 22.
  56. ;;
  57. ;; A list of recent changes can be found at
  58. ;; http://orgmode.org/Changes.html
  59. ;;
  60. ;;; Code:
  61. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  62. (defvar-local org-table-formula-constants-local nil
  63. "Local version of `org-table-formula-constants'.")
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (equal this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (require 'org-macs)
  81. (require 'org-compat)
  82. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  83. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  84. ;;
  85. ;; In Org buffers, the value of `outline-regexp' is that of
  86. ;; `org-outline-regexp'. The only function still directly relying on
  87. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  88. ;; job when `orgstruct-mode' is active.
  89. (defvar org-outline-regexp "\\*+ "
  90. "Regexp to match Org headlines.")
  91. (defvar org-outline-regexp-bol "^\\*+ "
  92. "Regexp to match Org headlines.
  93. This is similar to `org-outline-regexp' but additionally makes
  94. sure that we are at the beginning of the line.")
  95. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  96. "Matches a headline, putting stars and text into groups.
  97. Stars are put in group 1 and the trimmed body in group 2.")
  98. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  99. (declare-function org-add-archive-files "org-archive" (files))
  100. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  101. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
  102. (declare-function org-agenda-redo "org-agenda" (&optional all))
  103. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
  104. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  105. (declare-function org-beamer-mode "ox-beamer" ())
  106. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  107. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  108. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  109. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  110. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  111. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  112. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  113. (declare-function org-clock-update-time-maybe "org-clock" ())
  114. (declare-function org-clocktable-shift "org-clock" (dir n))
  115. (declare-function org-element-at-point "org-element" ())
  116. (declare-function org-element-cache-refresh "org-element" (pos))
  117. (declare-function org-element-cache-reset "org-element" (&optional all))
  118. (declare-function org-element-contents "org-element" (element))
  119. (declare-function org-element-context "org-element" (&optional element))
  120. (declare-function org-element-copy "org-element" (datum))
  121. (declare-function org-element-interpret-data "org-element" (data &optional parent))
  122. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  123. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  124. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  125. (declare-function org-element-property "org-element" (property element))
  126. (declare-function org-element-put-property "org-element" (element property value))
  127. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  128. (declare-function org-element-type "org-element" (element))
  129. (declare-function org-element-update-syntax "org-element" ())
  130. (declare-function org-id-find-id-file "org-id" (id))
  131. (declare-function org-id-get-create "org-id" (&optional force))
  132. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  133. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  134. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  135. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  136. (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
  137. (declare-function org-table-align "org-table" ())
  138. (declare-function org-table-begin "org-table" (&optional table-type))
  139. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  140. (declare-function org-table-blank-field "org-table" ())
  141. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  142. (declare-function org-table-edit-field "org-table" (arg))
  143. (declare-function org-table-end "org-table" (&optional table-type))
  144. (declare-function org-table-end-of-field "org-table" (&optional n))
  145. (declare-function org-table-insert-row "org-table" (&optional arg))
  146. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  147. (declare-function org-table-maybe-eval-formula "org-table" ())
  148. (declare-function org-table-maybe-recalculate-line "org-table" ())
  149. (declare-function org-table-next-row "org-table" ())
  150. (declare-function org-table-paste-rectangle "org-table" ())
  151. (declare-function org-table-wrap-region "org-table" (arg))
  152. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  153. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  154. (declare-function orgtbl-mode "org-table" (&optional arg))
  155. (defsubst org-uniquify (list)
  156. "Non-destructively remove duplicate elements from LIST."
  157. (let ((res (copy-sequence list))) (delete-dups res)))
  158. (defsubst org-get-at-bol (property)
  159. "Get text property PROPERTY at the beginning of line."
  160. (get-text-property (point-at-bol) property))
  161. (defsubst org-trim (s)
  162. "Remove whitespace at the beginning and the end of string S."
  163. (replace-regexp-in-string
  164. "\\`[ \t\n\r]+" ""
  165. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  166. ;; load languages based on value of `org-babel-load-languages'
  167. (defvar org-babel-load-languages)
  168. ;;;###autoload
  169. (defun org-babel-do-load-languages (sym value)
  170. "Load the languages defined in `org-babel-load-languages'."
  171. (set-default sym value)
  172. (mapc (lambda (pair)
  173. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  174. (if active
  175. (progn
  176. (require (intern (concat "ob-" lang))))
  177. (progn
  178. (funcall 'fmakunbound
  179. (intern (concat "org-babel-execute:" lang)))
  180. (funcall 'fmakunbound
  181. (intern (concat "org-babel-expand-body:" lang)))))))
  182. org-babel-load-languages))
  183. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  184. ;;;###autoload
  185. (defun org-babel-load-file (file &optional compile)
  186. "Load Emacs Lisp source code blocks in the Org-mode FILE.
  187. This function exports the source code using `org-babel-tangle'
  188. and then loads the resulting file using `load-file'. With prefix
  189. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  190. file to byte-code before it is loaded."
  191. (interactive "fFile to load: \nP")
  192. (let* ((age (lambda (file)
  193. (float-time
  194. (time-subtract (current-time)
  195. (nth 5 (or (file-attributes (file-truename file))
  196. (file-attributes file)))))))
  197. (base-name (file-name-sans-extension file))
  198. (exported-file (concat base-name ".el")))
  199. ;; tangle if the org-mode file is newer than the elisp file
  200. (unless (and (file-exists-p exported-file)
  201. (> (funcall age file) (funcall age exported-file)))
  202. ;; Tangle-file traversal returns reversed list of tangled files
  203. ;; and we want to evaluate the first target.
  204. (setq exported-file
  205. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  206. (message "%s %s"
  207. (if compile
  208. (progn (byte-compile-file exported-file 'load)
  209. "Compiled and loaded")
  210. (progn (load-file exported-file) "Loaded"))
  211. exported-file)))
  212. (defcustom org-babel-load-languages '((emacs-lisp . t))
  213. "Languages which can be evaluated in Org-mode buffers.
  214. This list can be used to load support for any of the languages
  215. below, note that each language will depend on a different set of
  216. system executables and/or Emacs modes. When a language is
  217. \"loaded\", then code blocks in that language can be evaluated
  218. with `org-babel-execute-src-block' bound by default to C-c
  219. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  220. be set to remove code block evaluation from the C-c C-c
  221. keybinding. By default only Emacs Lisp (which has no
  222. requirements) is loaded."
  223. :group 'org-babel
  224. :set 'org-babel-do-load-languages
  225. :version "24.1"
  226. :type '(alist :tag "Babel Languages"
  227. :key-type
  228. (choice
  229. (const :tag "Awk" awk)
  230. (const :tag "C" C)
  231. (const :tag "R" R)
  232. (const :tag "Asymptote" asymptote)
  233. (const :tag "Calc" calc)
  234. (const :tag "Clojure" clojure)
  235. (const :tag "CSS" css)
  236. (const :tag "Ditaa" ditaa)
  237. (const :tag "Dot" dot)
  238. (const :tag "Emacs Lisp" emacs-lisp)
  239. (const :tag "Forth" forth)
  240. (const :tag "Fortran" fortran)
  241. (const :tag "Gnuplot" gnuplot)
  242. (const :tag "Haskell" haskell)
  243. (const :tag "IO" io)
  244. (const :tag "J" J)
  245. (const :tag "Java" java)
  246. (const :tag "Javascript" js)
  247. (const :tag "LaTeX" latex)
  248. (const :tag "Ledger" ledger)
  249. (const :tag "Lilypond" lilypond)
  250. (const :tag "Lisp" lisp)
  251. (const :tag "Makefile" makefile)
  252. (const :tag "Maxima" maxima)
  253. (const :tag "Matlab" matlab)
  254. (const :tag "Mscgen" mscgen)
  255. (const :tag "Ocaml" ocaml)
  256. (const :tag "Octave" octave)
  257. (const :tag "Org" org)
  258. (const :tag "Perl" perl)
  259. (const :tag "Pico Lisp" picolisp)
  260. (const :tag "PlantUML" plantuml)
  261. (const :tag "Python" python)
  262. (const :tag "Ruby" ruby)
  263. (const :tag "Sass" sass)
  264. (const :tag "Scala" scala)
  265. (const :tag "Scheme" scheme)
  266. (const :tag "Screen" screen)
  267. (const :tag "Shell Script" shell)
  268. (const :tag "Shen" shen)
  269. (const :tag "Sql" sql)
  270. (const :tag "Sqlite" sqlite)
  271. (const :tag "Stan" stan)
  272. (const :tag "ebnf2ps" ebnf2ps))
  273. :value-type (boolean :tag "Activate" :value t)))
  274. ;;;; Customization variables
  275. (defcustom org-clone-delete-id nil
  276. "Remove ID property of clones of a subtree.
  277. When non-nil, clones of a subtree don't inherit the ID property.
  278. Otherwise they inherit the ID property with a new unique
  279. identifier."
  280. :type 'boolean
  281. :version "24.1"
  282. :group 'org-id)
  283. ;;; Version
  284. (org-check-version)
  285. ;;;###autoload
  286. (defun org-version (&optional here full message)
  287. "Show the org-mode version.
  288. Interactively, or when MESSAGE is non-nil, show it in echo area.
  289. With prefix argument, or when HERE is non-nil, insert it at point.
  290. In non-interactive uses, a reduced version string is output unless
  291. FULL is given."
  292. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  293. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  294. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  295. (load-suffixes (list ".el"))
  296. (org-install-dir
  297. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  298. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  299. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  300. (let* ((load-suffixes save-load-suffixes)
  301. (org-version (org-release))
  302. (git-version (org-git-version))
  303. (version (format "Org-mode version %s (%s @ %s)"
  304. org-version
  305. git-version
  306. (if org-install-dir
  307. (if (string= org-dir org-install-dir)
  308. org-install-dir
  309. (concat "mixed installation! " org-install-dir " and " org-dir))
  310. "org-loaddefs.el can not be found!")))
  311. (version1 (if full version org-version)))
  312. (when here (insert version1))
  313. (when message (message "%s" version1))
  314. version1)))
  315. (defconst org-version (org-version))
  316. ;;; Syntax Constants
  317. ;;;; Block
  318. (defconst org-block-regexp
  319. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  320. "Regular expression for hiding blocks.")
  321. (defconst org-dblock-start-re
  322. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  323. "Matches the start line of a dynamic block, with parameters.")
  324. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  325. "Matches the end of a dynamic block.")
  326. ;;;; Clock and Planning
  327. (defconst org-clock-string "CLOCK:"
  328. "String used as prefix for timestamps clocking work hours on an item.")
  329. (defvar org-closed-string "CLOSED:"
  330. "String used as the prefix for timestamps logging closing a TODO entry.")
  331. (defvar org-deadline-string "DEADLINE:"
  332. "String to mark deadline entries.
  333. A deadline is this string, followed by a time stamp. Should be a word,
  334. terminated by a colon. You can insert a schedule keyword and
  335. a timestamp with \\[org-deadline].")
  336. (defvar org-scheduled-string "SCHEDULED:"
  337. "String to mark scheduled TODO entries.
  338. A schedule is this string, followed by a time stamp. Should be a word,
  339. terminated by a colon. You can insert a schedule keyword and
  340. a timestamp with \\[org-schedule].")
  341. (defconst org-ds-keyword-length
  342. (+ 2
  343. (apply #'max
  344. (mapcar #'length
  345. (list org-deadline-string org-scheduled-string
  346. org-clock-string org-closed-string))))
  347. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  348. (defconst org-planning-line-re
  349. (concat "^[ \t]*"
  350. (regexp-opt
  351. (list org-closed-string org-deadline-string org-scheduled-string)
  352. t))
  353. "Matches a line with planning info.
  354. Matched keyword is in group 1.")
  355. (defconst org-clock-line-re
  356. (concat "^[ \t]*" org-clock-string)
  357. "Matches a line with clock info.")
  358. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  359. "Matches the DEADLINE keyword.")
  360. (defconst org-deadline-time-regexp
  361. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  362. "Matches the DEADLINE keyword together with a time stamp.")
  363. (defconst org-deadline-time-hour-regexp
  364. (concat "\\<" org-deadline-string
  365. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  366. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  367. (defconst org-deadline-line-regexp
  368. (concat "\\<\\(" org-deadline-string "\\).*")
  369. "Matches the DEADLINE keyword and the rest of the line.")
  370. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  371. "Matches the SCHEDULED keyword.")
  372. (defconst org-scheduled-time-regexp
  373. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  374. "Matches the SCHEDULED keyword together with a time stamp.")
  375. (defconst org-scheduled-time-hour-regexp
  376. (concat "\\<" org-scheduled-string
  377. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  378. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  379. (defconst org-closed-time-regexp
  380. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  381. "Matches the CLOSED keyword together with a time stamp.")
  382. (defconst org-keyword-time-regexp
  383. (concat "\\<"
  384. (regexp-opt
  385. (list org-scheduled-string org-deadline-string org-closed-string
  386. org-clock-string)
  387. t)
  388. " *[[<]\\([^]>]+\\)[]>]")
  389. "Matches any of the 4 keywords, together with the time stamp.")
  390. (defconst org-keyword-time-not-clock-regexp
  391. (concat
  392. "\\<"
  393. (regexp-opt
  394. (list org-scheduled-string org-deadline-string org-closed-string) t)
  395. " *[[<]\\([^]>]+\\)[]>]")
  396. "Matches any of the 3 keywords, together with the time stamp.")
  397. (defconst org-maybe-keyword-time-regexp
  398. (concat "\\(\\<"
  399. (regexp-opt
  400. (list org-scheduled-string org-deadline-string org-closed-string
  401. org-clock-string)
  402. t)
  403. "\\)?"
  404. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  405. "\\|"
  406. "<%%([^\r\n>]*>\\)")
  407. "Matches a timestamp, possibly preceded by a keyword.")
  408. (defconst org-all-time-keywords
  409. (mapcar (lambda (w) (substring w 0 -1))
  410. (list org-scheduled-string org-deadline-string
  411. org-clock-string org-closed-string))
  412. "List of time keywords.")
  413. ;;;; Drawer
  414. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  415. "Matches first or last line of a hidden block.
  416. Group 1 contains drawer's name or \"END\".")
  417. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  418. "Regular expression matching the first line of a property drawer.")
  419. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  420. "Regular expression matching the last line of a property drawer.")
  421. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  422. "Regular expression matching the first line of a clock drawer.")
  423. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  424. "Regular expression matching the last line of a clock drawer.")
  425. (defconst org-property-drawer-re
  426. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  427. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  428. "[ \t]*:END:[ \t]*$")
  429. "Matches an entire property drawer.")
  430. (defconst org-clock-drawer-re
  431. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  432. org-clock-drawer-end-re "\\)\n?")
  433. "Matches an entire clock drawer.")
  434. ;;;; Headline
  435. (defconst org-heading-keyword-regexp-format
  436. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  437. "Printf format for a regexp matching a headline with some keyword.
  438. This regexp will match the headline of any node which has the
  439. exact keyword that is put into the format. The keyword isn't in
  440. any group by default, but the stars and the body are.")
  441. (defconst org-heading-keyword-maybe-regexp-format
  442. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  443. "Printf format for a regexp matching a headline, possibly with some keyword.
  444. This regexp can match any headline with the specified keyword, or
  445. without a keyword. The keyword isn't in any group by default,
  446. but the stars and the body are.")
  447. (defconst org-archive-tag "ARCHIVE"
  448. "The tag that marks a subtree as archived.
  449. An archived subtree does not open during visibility cycling, and does
  450. not contribute to the agenda listings.")
  451. (defconst org-comment-string "COMMENT"
  452. "Entries starting with this keyword will never be exported.
  453. An entry can be toggled between COMMENT and normal with
  454. \\[org-toggle-comment].")
  455. ;;;; LaTeX Environments and Fragments
  456. (defconst org-latex-regexps
  457. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  458. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  459. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  460. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  461. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  462. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  463. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  464. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  465. "Regular expressions for matching embedded LaTeX.")
  466. ;;;; Node Property
  467. (defconst org-effort-property "Effort"
  468. "The property that is being used to keep track of effort estimates.
  469. Effort estimates given in this property need to have the format H:MM.")
  470. ;;;; Table
  471. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  472. "Detect an org-type or table-type table.")
  473. (defconst org-table-line-regexp "^[ \t]*|"
  474. "Detect an org-type table line.")
  475. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  476. "Detect an org-type table line.")
  477. (defconst org-table-hline-regexp "^[ \t]*|-"
  478. "Detect an org-type table hline.")
  479. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  480. "Detect a table-type table hline.")
  481. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  482. "Detect the first line outside a table when searching from within it.
  483. This works for both table types.")
  484. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  485. "Detect a #+TBLFM line.")
  486. ;;;; Timestamp
  487. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  488. "Regular expression for fast time stamp matching.")
  489. (defconst org-ts-regexp-inactive
  490. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  491. "Regular expression for fast inactive time stamp matching.")
  492. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  493. "Regular expression for fast time stamp matching.")
  494. (defconst org-ts-regexp0
  495. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  496. "Regular expression matching time strings for analysis.
  497. This one does not require the space after the date, so it can be used
  498. on a string that terminates immediately after the date.")
  499. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  500. "Regular expression matching time strings for analysis.")
  501. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  502. "Regular expression matching time stamps, with groups.")
  503. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  504. "Regular expression matching time stamps (also [..]), with groups.")
  505. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  506. "Regular expression matching a time stamp range.")
  507. (defconst org-tr-regexp-both
  508. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  509. "Regular expression matching a time stamp range.")
  510. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  511. org-ts-regexp "\\)?")
  512. "Regular expression matching a time stamp or time stamp range.")
  513. (defconst org-tsr-regexp-both
  514. (concat org-ts-regexp-both "\\(--?-?"
  515. org-ts-regexp-both "\\)?")
  516. "Regular expression matching a time stamp or time stamp range.
  517. The time stamps may be either active or inactive.")
  518. (defconst org-repeat-re
  519. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  520. "Regular expression for specifying repeated events.
  521. After a match, group 1 contains the repeat expression.")
  522. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  523. "Formats for `format-time-string' which are used for time stamps.")
  524. ;;; The custom variables
  525. (defgroup org nil
  526. "Outline-based notes management and organizer."
  527. :tag "Org"
  528. :group 'outlines
  529. :group 'calendar)
  530. (defcustom org-mode-hook nil
  531. "Mode hook for Org-mode, run after the mode was turned on."
  532. :group 'org
  533. :type 'hook)
  534. (defcustom org-load-hook nil
  535. "Hook that is run after org.el has been loaded."
  536. :group 'org
  537. :type 'hook)
  538. (defcustom org-log-buffer-setup-hook nil
  539. "Hook that is run after an Org log buffer is created."
  540. :group 'org
  541. :version "24.1"
  542. :type 'hook)
  543. (defvar org-modules) ; defined below
  544. (defvar org-modules-loaded nil
  545. "Have the modules been loaded already?")
  546. (defun org-load-modules-maybe (&optional force)
  547. "Load all extensions listed in `org-modules'."
  548. (when (or force (not org-modules-loaded))
  549. (mapc (lambda (ext)
  550. (condition-case nil (require ext)
  551. (error (message "Problems while trying to load feature `%s'" ext))))
  552. org-modules)
  553. (setq org-modules-loaded t)))
  554. (defun org-set-modules (var value)
  555. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  556. (set var value)
  557. (when (featurep 'org)
  558. (org-load-modules-maybe 'force)
  559. (org-element-cache-reset 'all)))
  560. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  561. "Modules that should always be loaded together with org.el.
  562. If a description starts with <C>, the file is not part of Emacs
  563. and loading it will require that you have downloaded and properly
  564. installed the Org mode distribution.
  565. You can also use this system to load external packages (i.e. neither Org
  566. core modules, nor modules from the CONTRIB directory). Just add symbols
  567. to the end of the list. If the package is called org-xyz.el, then you need
  568. to add the symbol `xyz', and the package must have a call to:
  569. (provide \\='org-xyz)
  570. For export specific modules, see also `org-export-backends'."
  571. :group 'org
  572. :set 'org-set-modules
  573. :version "24.4"
  574. :package-version '(Org . "8.0")
  575. :type
  576. '(set :greedy t
  577. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  578. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  579. (const :tag " crypt: Encryption of subtrees" org-crypt)
  580. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  581. (const :tag " docview: Links to doc-view buffers" org-docview)
  582. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  583. (const :tag " habit: Track your consistency with habits" org-habit)
  584. (const :tag " id: Global IDs for identifying entries" org-id)
  585. (const :tag " info: Links to Info nodes" org-info)
  586. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  587. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  588. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  589. (const :tag " mouse: Additional mouse support" org-mouse)
  590. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  591. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  592. (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
  593. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  594. (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
  595. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  596. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  597. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  598. (const :tag "C collector: Collect properties into tables" org-collector)
  599. (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  600. (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
  601. (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
  602. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  603. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  604. (const :tag "C eval: Include command output as text" org-eval)
  605. (const :tag "C eww: Store link to url of eww" org-eww)
  606. (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
  607. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  608. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  609. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  610. (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
  611. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  612. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  613. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  614. (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
  615. (const :tag "C man: Support for links to manpages in Org-mode" org-man)
  616. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  617. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  618. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  619. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  620. (const :tag "C registry: A registry for Org-mode links" org-registry)
  621. (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
  622. (const :tag "C secretary: Team management with org-mode" org-secretary)
  623. (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
  624. (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
  625. (const :tag "C track: Keep up with Org-mode development" org-track)
  626. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  627. (const :tag "C vm: Links to VM folders/messages" org-vm)
  628. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  629. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  630. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  631. (defvar org-export-registered-backends) ; From ox.el.
  632. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  633. (declare-function org-export-backend-name "ox" (backend))
  634. (defcustom org-export-backends '(ascii html icalendar latex)
  635. "List of export back-ends that should be always available.
  636. If a description starts with <C>, the file is not part of Emacs
  637. and loading it will require that you have downloaded and properly
  638. installed the Org mode distribution.
  639. Unlike to `org-modules', libraries in this list will not be
  640. loaded along with Org, but only once the export framework is
  641. needed.
  642. This variable needs to be set before org.el is loaded. If you
  643. need to make a change while Emacs is running, use the customize
  644. interface or run the following code, where VAL stands for the new
  645. value of the variable, after updating it:
  646. (progn
  647. (setq org-export-registered-backends
  648. (cl-remove-if-not
  649. (lambda (backend)
  650. (let ((name (org-export-backend-name backend)))
  651. (or (memq name val)
  652. (catch \\='parentp
  653. (dolist (b val)
  654. (and (org-export-derived-backend-p b name)
  655. (throw \\='parentp t)))))))
  656. org-export-registered-backends))
  657. (let ((new-list (mapcar #\\='org-export-backend-name
  658. org-export-registered-backends)))
  659. (dolist (backend val)
  660. (cond
  661. ((not (load (format \"ox-%s\" backend) t t))
  662. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  663. backend))
  664. ((not (memq backend new-list)) (push backend new-list))))
  665. (set-default \\='org-export-backends new-list)))
  666. Adding a back-end to this list will also pull the back-end it
  667. depends on, if any."
  668. :group 'org
  669. :group 'org-export
  670. :version "24.4"
  671. :package-version '(Org . "8.0")
  672. :initialize 'custom-initialize-set
  673. :set (lambda (var val)
  674. (if (not (featurep 'ox)) (set-default var val)
  675. ;; Any back-end not required anymore (not present in VAL and not
  676. ;; a parent of any back-end in the new value) is removed from the
  677. ;; list of registered back-ends.
  678. (setq org-export-registered-backends
  679. (cl-remove-if-not
  680. (lambda (backend)
  681. (let ((name (org-export-backend-name backend)))
  682. (or (memq name val)
  683. (catch 'parentp
  684. (dolist (b val)
  685. (and (org-export-derived-backend-p b name)
  686. (throw 'parentp t)))))))
  687. org-export-registered-backends))
  688. ;; Now build NEW-LIST of both new back-ends and required
  689. ;; parents.
  690. (let ((new-list (mapcar #'org-export-backend-name
  691. org-export-registered-backends)))
  692. (dolist (backend val)
  693. (cond
  694. ((not (load (format "ox-%s" backend) t t))
  695. (message "Problems while trying to load export back-end `%s'"
  696. backend))
  697. ((not (memq backend new-list)) (push backend new-list))))
  698. ;; Set VAR to that list with fixed dependencies.
  699. (set-default var new-list))))
  700. :type '(set :greedy t
  701. (const :tag " ascii Export buffer to ASCII format" ascii)
  702. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  703. (const :tag " html Export buffer to HTML format" html)
  704. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  705. (const :tag " latex Export buffer to LaTeX format" latex)
  706. (const :tag " man Export buffer to MAN format" man)
  707. (const :tag " md Export buffer to Markdown format" md)
  708. (const :tag " odt Export buffer to ODT format" odt)
  709. (const :tag " org Export buffer to Org format" org)
  710. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  711. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  712. (const :tag "C deck Export buffer to deck.js presentations" deck)
  713. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  714. (const :tag "C groff Export buffer to Groff format" groff)
  715. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  716. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  717. (const :tag "C s5 Export buffer to s5 presentations" s5)
  718. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  719. (eval-after-load 'ox
  720. '(mapc
  721. (lambda (backend)
  722. (condition-case nil (require (intern (format "ox-%s" backend)))
  723. (error (message "Problems while trying to load export back-end `%s'"
  724. backend))))
  725. org-export-backends))
  726. (defcustom org-support-shift-select nil
  727. "Non-nil means make shift-cursor commands select text when possible.
  728. \\<org-mode-map>\
  729. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  730. start selecting a region, or enlarge regions started in this way.
  731. In Org-mode, in special contexts, these same keys are used for
  732. other purposes, important enough to compete with shift selection.
  733. Org tries to balance these needs by supporting `shift-select-mode'
  734. outside these special contexts, under control of this variable.
  735. The default of this variable is nil, to avoid confusing behavior. Shifted
  736. cursor keys will then execute Org commands in the following contexts:
  737. - on a headline, changing TODO state (left/right) and priority (up/down)
  738. - on a time stamp, changing the time
  739. - in a plain list item, changing the bullet type
  740. - in a property definition line, switching between allowed values
  741. - in the BEGIN line of a clock table (changing the time block).
  742. Outside these contexts, the commands will throw an error.
  743. When this variable is t and the cursor is not in a special
  744. context, Org-mode will support shift-selection for making and
  745. enlarging regions. To make this more effective, the bullet
  746. cycling will no longer happen anywhere in an item line, but only
  747. if the cursor is exactly on the bullet.
  748. If you set this variable to the symbol `always', then the keys
  749. will not be special in headlines, property lines, and item lines,
  750. to make shift selection work there as well. If this is what you
  751. want, you can use the following alternative commands:
  752. `\\[org-todo]' and `\\[org-priority]' \
  753. to change TODO state and priority,
  754. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  755. can be used to switch TODO sets,
  756. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  757. and properties can be edited by hand or in column view.
  758. However, when the cursor is on a timestamp, shift-cursor commands
  759. will still edit the time stamp - this is just too good to give up.
  760. XEmacs user should have this variable set to nil, because
  761. `shift-select-mode' is in Emacs 23 or later only."
  762. :group 'org
  763. :type '(choice
  764. (const :tag "Never" nil)
  765. (const :tag "When outside special context" t)
  766. (const :tag "Everywhere except timestamps" always)))
  767. (defcustom org-loop-over-headlines-in-active-region nil
  768. "Shall some commands act upon headlines in the active region?
  769. When set to t, some commands will be performed in all headlines
  770. within the active region.
  771. When set to `start-level', some commands will be performed in all
  772. headlines within the active region, provided that these headlines
  773. are of the same level than the first one.
  774. When set to a string, those commands will be performed on the
  775. matching headlines within the active region. Such string must be
  776. a tags/property/todo match as it is used in the agenda tags view.
  777. The list of commands is: `org-schedule', `org-deadline',
  778. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  779. `org-archive-to-archive-sibling'. The archiving commands skip
  780. already archived entries."
  781. :type '(choice (const :tag "Don't loop" nil)
  782. (const :tag "All headlines in active region" t)
  783. (const :tag "In active region, headlines at the same level than the first one" start-level)
  784. (string :tag "Tags/Property/Todo matcher"))
  785. :version "24.1"
  786. :group 'org-todo
  787. :group 'org-archive)
  788. (defgroup org-startup nil
  789. "Options concerning startup of Org-mode."
  790. :tag "Org Startup"
  791. :group 'org)
  792. (defcustom org-startup-folded t
  793. "Non-nil means entering Org-mode will switch to OVERVIEW.
  794. This can also be configured on a per-file basis by adding one of
  795. the following lines anywhere in the buffer:
  796. #+STARTUP: fold (or `overview', this is equivalent)
  797. #+STARTUP: nofold (or `showall', this is equivalent)
  798. #+STARTUP: content
  799. #+STARTUP: showeverything
  800. By default, this option is ignored when Org opens agenda files
  801. for the first time. If you want the agenda to honor the startup
  802. option, set `org-agenda-inhibit-startup' to nil."
  803. :group 'org-startup
  804. :type '(choice
  805. (const :tag "nofold: show all" nil)
  806. (const :tag "fold: overview" t)
  807. (const :tag "content: all headlines" content)
  808. (const :tag "show everything, even drawers" showeverything)))
  809. (defcustom org-startup-truncated t
  810. "Non-nil means entering Org-mode will set `truncate-lines'.
  811. This is useful since some lines containing links can be very long and
  812. uninteresting. Also tables look terrible when wrapped."
  813. :group 'org-startup
  814. :type 'boolean)
  815. (defcustom org-startup-indented nil
  816. "Non-nil means turn on `org-indent-mode' on startup.
  817. This can also be configured on a per-file basis by adding one of
  818. the following lines anywhere in the buffer:
  819. #+STARTUP: indent
  820. #+STARTUP: noindent"
  821. :group 'org-structure
  822. :type '(choice
  823. (const :tag "Not" nil)
  824. (const :tag "Globally (slow on startup in large files)" t)))
  825. (defcustom org-use-sub-superscripts t
  826. "Non-nil means interpret \"_\" and \"^\" for display.
  827. If you want to control how Org exports those characters, see
  828. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  829. used to be an alias for `org-export-with-sub-superscripts' in
  830. Org <8.0, it is not anymore.
  831. When this option is turned on, you can use TeX-like syntax for
  832. sub- and superscripts within the buffer. Several characters after
  833. \"_\" or \"^\" will be considered as a single item - so grouping
  834. with {} is normally not needed. For example, the following things
  835. will be parsed as single sub- or superscripts:
  836. 10^24 or 10^tau several digits will be considered 1 item.
  837. 10^-12 or 10^-tau a leading sign with digits or a word
  838. x^2-y^3 will be read as x^2 - y^3, because items are
  839. terminated by almost any nonword/nondigit char.
  840. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  841. Still, ambiguity is possible. So when in doubt, use {} to enclose
  842. the sub/superscript. If you set this variable to the symbol `{}',
  843. the braces are *required* in order to trigger interpretations as
  844. sub/superscript. This can be helpful in documents that need \"_\"
  845. frequently in plain text."
  846. :group 'org-startup
  847. :version "24.4"
  848. :package-version '(Org . "8.0")
  849. :type '(choice
  850. (const :tag "Always interpret" t)
  851. (const :tag "Only with braces" {})
  852. (const :tag "Never interpret" nil)))
  853. (defcustom org-startup-with-beamer-mode nil
  854. "Non-nil means turn on `org-beamer-mode' on startup.
  855. This can also be configured on a per-file basis by adding one of
  856. the following lines anywhere in the buffer:
  857. #+STARTUP: beamer"
  858. :group 'org-startup
  859. :version "24.1"
  860. :type 'boolean)
  861. (defcustom org-startup-align-all-tables nil
  862. "Non-nil means align all tables when visiting a file.
  863. This is useful when the column width in tables is forced with <N> cookies
  864. in table fields. Such tables will look correct only after the first re-align.
  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: align
  868. #+STARTUP: noalign"
  869. :group 'org-startup
  870. :type 'boolean)
  871. (defcustom org-startup-with-inline-images nil
  872. "Non-nil means show inline images when loading a new Org file.
  873. This can also be configured on a per-file basis by adding one of
  874. the following lines anywhere in the buffer:
  875. #+STARTUP: inlineimages
  876. #+STARTUP: noinlineimages"
  877. :group 'org-startup
  878. :version "24.1"
  879. :type 'boolean)
  880. (defcustom org-startup-with-latex-preview nil
  881. "Non-nil means preview LaTeX fragments when loading a new Org file.
  882. This can also be configured on a per-file basis by adding one of
  883. the following lines anywhere in the buffer:
  884. #+STARTUP: latexpreview
  885. #+STARTUP: nolatexpreview"
  886. :group 'org-startup
  887. :version "24.4"
  888. :package-version '(Org . "8.0")
  889. :type 'boolean)
  890. (defcustom org-insert-mode-line-in-empty-file nil
  891. "Non-nil means insert the first line setting Org-mode in empty files.
  892. When the function `org-mode' is called interactively in an empty file, this
  893. normally means that the file name does not automatically trigger Org-mode.
  894. To ensure that the file will always be in Org-mode in the future, a
  895. line enforcing Org-mode will be inserted into the buffer, if this option
  896. has been set."
  897. :group 'org-startup
  898. :type 'boolean)
  899. (defcustom org-replace-disputed-keys nil
  900. "Non-nil means use alternative key bindings for some keys.
  901. Org-mode uses S-<cursor> keys for changing timestamps and priorities.
  902. These keys are also used by other packages like shift-selection-mode'
  903. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  904. If you want to use Org-mode together with one of these other modes,
  905. or more generally if you would like to move some Org-mode commands to
  906. other keys, set this variable and configure the keys with the variable
  907. `org-disputed-keys'.
  908. This option is only relevant at load-time of Org-mode, and must be set
  909. *before* org.el is loaded. Changing it requires a restart of Emacs to
  910. become effective."
  911. :group 'org-startup
  912. :type 'boolean)
  913. (defcustom org-use-extra-keys nil
  914. "Non-nil means use extra key sequence definitions for certain commands.
  915. This happens automatically if you run XEmacs or if `window-system'
  916. is nil. This variable lets you do the same manually. You must
  917. set it before loading org.
  918. Example: on Carbon Emacs 22 running graphically, with an external
  919. keyboard on a Powerbook, the default way of setting M-left might
  920. not work for either Alt or ESC. Setting this variable will make
  921. it work for ESC."
  922. :group 'org-startup
  923. :type 'boolean)
  924. (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  925. (defcustom org-disputed-keys
  926. '(([(shift up)] . [(meta p)])
  927. ([(shift down)] . [(meta n)])
  928. ([(shift left)] . [(meta -)])
  929. ([(shift right)] . [(meta +)])
  930. ([(control shift right)] . [(meta shift +)])
  931. ([(control shift left)] . [(meta shift -)]))
  932. "Keys for which Org-mode and other modes compete.
  933. This is an alist, cars are the default keys, second element specifies
  934. the alternative to use when `org-replace-disputed-keys' is t.
  935. Keys can be specified in any syntax supported by `define-key'.
  936. The value of this option takes effect only at Org-mode's startup,
  937. therefore you'll have to restart Emacs to apply it after changing."
  938. :group 'org-startup
  939. :type 'alist)
  940. (defun org-key (key)
  941. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  942. Or return the original if not disputed.
  943. Also apply the translations defined in `org-xemacs-key-equivalents'."
  944. (when org-replace-disputed-keys
  945. (let* ((nkey (key-description key))
  946. (x (org-find-if (lambda (x)
  947. (equal (key-description (car x)) nkey))
  948. org-disputed-keys)))
  949. (setq key (if x (cdr x) key))))
  950. (when (featurep 'xemacs)
  951. (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
  952. key)
  953. (defun org-find-if (predicate seq)
  954. (catch 'exit
  955. (while seq
  956. (if (funcall predicate (car seq))
  957. (throw 'exit (car seq))
  958. (pop seq)))))
  959. (defun org-defkey (keymap key def)
  960. "Define a key, possibly translated, as returned by `org-key'."
  961. (define-key keymap (org-key key) def))
  962. (defcustom org-ellipsis nil
  963. "The ellipsis to use in the Org-mode outline.
  964. When nil, just use the standard three dots.
  965. When a string, use that string instead.
  966. When a face, use the standard 3 dots, but with the specified face.
  967. The change affects only Org-mode (which will then use its own display table).
  968. Changing this requires executing \\[org-mode] in a buffer to become
  969. effective."
  970. :group 'org-startup
  971. :type '(choice (const :tag "Default" nil)
  972. (face :tag "Face" :value org-warning)
  973. (string :tag "String" :value "...#")))
  974. (defvar org-display-table nil
  975. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  976. (defgroup org-keywords nil
  977. "Keywords in Org-mode."
  978. :tag "Org Keywords"
  979. :group 'org)
  980. (defcustom org-closed-keep-when-no-todo nil
  981. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  982. :group 'org-todo
  983. :group 'org-keywords
  984. :version "24.4"
  985. :package-version '(Org . "8.0")
  986. :type 'boolean)
  987. (defgroup org-structure nil
  988. "Options concerning the general structure of Org-mode files."
  989. :tag "Org Structure"
  990. :group 'org)
  991. (defgroup org-reveal-location nil
  992. "Options about how to make context of a location visible."
  993. :tag "Org Reveal Location"
  994. :group 'org-structure)
  995. (defcustom org-show-context-detail '((isearch . lineage)
  996. (bookmark-jump . lineage)
  997. (default . ancestors))
  998. "Alist between context and visibility span when revealing a location.
  999. \\<org-mode-map>Some actions may move point into invisible
  1000. locations. As a consequence, Org always expose a neighborhood
  1001. around point. How much is shown depends on the initial action,
  1002. or context. Valid contexts are
  1003. agenda when exposing an entry from the agenda
  1004. org-goto when using the command `org-goto' (\\[org-goto])
  1005. occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
  1006. tags-tree when constructing a sparse tree based on tags matches
  1007. link-search when exposing search matches associated with a link
  1008. mark-goto when exposing the jump goal of a mark
  1009. bookmark-jump when exposing a bookmark location
  1010. isearch when exiting from an incremental search
  1011. default default for all contexts not set explicitly
  1012. Allowed visibility spans are
  1013. minimal show current headline; if point is not on headline,
  1014. also show entry
  1015. local show current headline, entry and next headline
  1016. ancestors show current headline and its direct ancestors; if
  1017. point is not on headline, also show entry
  1018. lineage show current headline, its direct ancestors and all
  1019. their children; if point is not on headline, also show
  1020. entry and first child
  1021. tree show current headline, its direct ancestors and all
  1022. their children; if point is not on headline, also show
  1023. entry and all children
  1024. canonical show current headline, its direct ancestors along with
  1025. their entries and children; if point is not located on
  1026. the headline, also show current entry and all children
  1027. As special cases, a nil or t value means show all contexts in
  1028. `minimal' or `canonical' view, respectively.
  1029. Some views can make displayed information very compact, but also
  1030. make it harder to edit the location of the match. In such
  1031. a case, use the command `org-reveal' (\\[org-reveal]) to show
  1032. more context."
  1033. :group 'org-reveal-location
  1034. :version "25.1"
  1035. :package-version '(Org . "8.3")
  1036. :type '(choice
  1037. (const :tag "Canonical" t)
  1038. (const :tag "Minimal" nil)
  1039. (repeat :greedy t :tag "Individual contexts"
  1040. (cons
  1041. (choice :tag "Context"
  1042. (const agenda)
  1043. (const org-goto)
  1044. (const occur-tree)
  1045. (const tags-tree)
  1046. (const link-search)
  1047. (const mark-goto)
  1048. (const bookmark-jump)
  1049. (const isearch)
  1050. (const default))
  1051. (choice :tag "Detail level"
  1052. (const minimal)
  1053. (const local)
  1054. (const ancestors)
  1055. (const lineage)
  1056. (const tree)
  1057. (const canonical))))))
  1058. (defcustom org-indirect-buffer-display 'other-window
  1059. "How should indirect tree buffers be displayed?
  1060. This applies to indirect buffers created with the commands
  1061. \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
  1062. Valid values are:
  1063. current-window Display in the current window
  1064. other-window Just display in another window.
  1065. dedicated-frame Create one new frame, and re-use it each time.
  1066. new-frame Make a new frame each time. Note that in this case
  1067. previously-made indirect buffers are kept, and you need to
  1068. kill these buffers yourself."
  1069. :group 'org-structure
  1070. :group 'org-agenda-windows
  1071. :type '(choice
  1072. (const :tag "In current window" current-window)
  1073. (const :tag "In current frame, other window" other-window)
  1074. (const :tag "Each time a new frame" new-frame)
  1075. (const :tag "One dedicated frame" dedicated-frame)))
  1076. (defcustom org-use-speed-commands nil
  1077. "Non-nil means activate single letter commands at beginning of a headline.
  1078. This may also be a function to test for appropriate locations where speed
  1079. commands should be active.
  1080. For example, to activate speed commands when the point is on any
  1081. star at the beginning of the headline, you can do this:
  1082. (setq org-use-speed-commands
  1083. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1084. :group 'org-structure
  1085. :type '(choice
  1086. (const :tag "Never" nil)
  1087. (const :tag "At beginning of headline stars" t)
  1088. (function)))
  1089. (defcustom org-speed-commands-user nil
  1090. "Alist of additional speed commands.
  1091. This list will be checked before `org-speed-commands-default'
  1092. when the variable `org-use-speed-commands' is non-nil
  1093. and when the cursor is at the beginning of a headline.
  1094. The car if each entry is a string with a single letter, which must
  1095. be assigned to `self-insert-command' in the global map.
  1096. The cdr is either a command to be called interactively, a function
  1097. to be called, or a form to be evaluated.
  1098. An entry that is just a list with a single string will be interpreted
  1099. as a descriptive headline that will be added when listing the speed
  1100. commands in the Help buffer using the `?' speed command."
  1101. :group 'org-structure
  1102. :type '(repeat :value ("k" . ignore)
  1103. (choice :value ("k" . ignore)
  1104. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1105. (cons :tag "Letter and Command"
  1106. (string :tag "Command letter")
  1107. (choice
  1108. (function)
  1109. (sexp))))))
  1110. (defcustom org-bookmark-names-plist
  1111. '(:last-capture "org-capture-last-stored"
  1112. :last-refile "org-refile-last-stored"
  1113. :last-capture-marker "org-capture-last-stored-marker")
  1114. "Names for bookmarks automatically set by some Org commands.
  1115. This can provide strings as names for a number of bookmarks Org sets
  1116. automatically. The following keys are currently implemented:
  1117. :last-capture
  1118. :last-capture-marker
  1119. :last-refile
  1120. When a key does not show up in the property list, the corresponding bookmark
  1121. is not set."
  1122. :group 'org-structure
  1123. :type 'plist)
  1124. (defgroup org-cycle nil
  1125. "Options concerning visibility cycling in Org-mode."
  1126. :tag "Org Cycle"
  1127. :group 'org-structure)
  1128. (defcustom org-cycle-skip-children-state-if-no-children t
  1129. "Non-nil means skip CHILDREN state in entries that don't have any."
  1130. :group 'org-cycle
  1131. :type 'boolean)
  1132. (defcustom org-cycle-max-level nil
  1133. "Maximum level which should still be subject to visibility cycling.
  1134. Levels higher than this will, for cycling, be treated as text, not a headline.
  1135. When `org-odd-levels-only' is set, a value of N in this variable actually
  1136. means 2N-1 stars as the limiting headline.
  1137. When nil, cycle all levels.
  1138. Note that the limiting level of cycling is also influenced by
  1139. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1140. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1141. than its value."
  1142. :group 'org-cycle
  1143. :type '(choice
  1144. (const :tag "No limit" nil)
  1145. (integer :tag "Maximum level")))
  1146. (defcustom org-hide-block-startup nil
  1147. "Non-nil means entering Org-mode will fold all blocks.
  1148. This can also be set in on a per-file basis with
  1149. #+STARTUP: hideblocks
  1150. #+STARTUP: showblocks"
  1151. :group 'org-startup
  1152. :group 'org-cycle
  1153. :type 'boolean)
  1154. (defcustom org-cycle-global-at-bob nil
  1155. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1156. This makes it possible to do global cycling without having to use S-TAB or
  1157. \\[universal-argument] TAB. For this special case to work, the first line
  1158. of the buffer must not be a headline -- it may be empty or some other text.
  1159. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1160. sure the cursor stays at the beginning of the buffer. When this option is
  1161. nil, don't do anything special at the beginning of the buffer."
  1162. :group 'org-cycle
  1163. :type 'boolean)
  1164. (defcustom org-cycle-level-after-item/entry-creation t
  1165. "Non-nil means cycle entry level or item indentation in new empty entries.
  1166. When the cursor is at the end of an empty headline, i.e., with only stars
  1167. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1168. and then all possible ancestor states, before returning to the original state.
  1169. This makes data entry extremely fast: M-RET to create a new headline,
  1170. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1171. When the cursor is at the end of an empty plain list item, one TAB will
  1172. make it a subitem, two or more tabs will back up to make this an item
  1173. higher up in the item hierarchy."
  1174. :group 'org-cycle
  1175. :type 'boolean)
  1176. (defcustom org-cycle-emulate-tab t
  1177. "Where should `org-cycle' emulate TAB.
  1178. nil Never
  1179. white Only in completely white lines
  1180. whitestart Only at the beginning of lines, before the first non-white char
  1181. t Everywhere except in headlines
  1182. exc-hl-bol Everywhere except at the start of a headline
  1183. If TAB is used in a place where it does not emulate TAB, the current subtree
  1184. visibility is cycled."
  1185. :group 'org-cycle
  1186. :type '(choice (const :tag "Never" nil)
  1187. (const :tag "Only in completely white lines" white)
  1188. (const :tag "Before first char in a line" whitestart)
  1189. (const :tag "Everywhere except in headlines" t)
  1190. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1191. (defcustom org-cycle-separator-lines 2
  1192. "Number of empty lines needed to keep an empty line between collapsed trees.
  1193. If you leave an empty line between the end of a subtree and the following
  1194. headline, this empty line is hidden when the subtree is folded.
  1195. Org-mode will leave (exactly) one empty line visible if the number of
  1196. empty lines is equal or larger to the number given in this variable.
  1197. So the default 2 means at least 2 empty lines after the end of a subtree
  1198. are needed to produce free space between a collapsed subtree and the
  1199. following headline.
  1200. If the number is negative, and the number of empty lines is at least -N,
  1201. all empty lines are shown.
  1202. Special case: when 0, never leave empty lines in collapsed view."
  1203. :group 'org-cycle
  1204. :type 'integer)
  1205. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1206. (defcustom org-pre-cycle-hook nil
  1207. "Hook that is run before visibility cycling is happening.
  1208. The function(s) in this hook must accept a single argument which indicates
  1209. the new state that will be set right after running this hook. The
  1210. argument is a symbol. Before a global state change, it can have the values
  1211. `overview', `content', or `all'. Before a local state change, it can have
  1212. the values `folded', `children', or `subtree'."
  1213. :group 'org-cycle
  1214. :type 'hook)
  1215. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1216. org-cycle-hide-drawers
  1217. org-cycle-show-empty-lines
  1218. org-optimize-window-after-visibility-change)
  1219. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1220. The function(s) in this hook must accept a single argument which indicates
  1221. the new state that was set by the most recent `org-cycle' command. The
  1222. argument is a symbol. After a global state change, it can have the values
  1223. `overview', `contents', or `all'. After a local state change, it can have
  1224. the values `folded', `children', or `subtree'."
  1225. :group 'org-cycle
  1226. :type 'hook
  1227. :version "25.1"
  1228. :package-version '(Org . "8.3"))
  1229. (defgroup org-edit-structure nil
  1230. "Options concerning structure editing in Org-mode."
  1231. :tag "Org Edit Structure"
  1232. :group 'org-structure)
  1233. (defcustom org-odd-levels-only nil
  1234. "Non-nil means skip even levels and only use odd levels for the outline.
  1235. This has the effect that two stars are being added/taken away in
  1236. promotion/demotion commands. It also influences how levels are
  1237. handled by the exporters.
  1238. Changing it requires restart of `font-lock-mode' to become effective
  1239. for fontification also in regions already fontified.
  1240. You may also set this on a per-file basis by adding one of the following
  1241. lines to the buffer:
  1242. #+STARTUP: odd
  1243. #+STARTUP: oddeven"
  1244. :group 'org-edit-structure
  1245. :group 'org-appearance
  1246. :type 'boolean)
  1247. (defcustom org-adapt-indentation t
  1248. "Non-nil means adapt indentation to outline node level.
  1249. When this variable is set, Org assumes that you write outlines by
  1250. indenting text in each node to align with the headline (after the
  1251. stars). The following issues are influenced by this variable:
  1252. - The indentation is increased by one space in a demotion
  1253. command, and decreased by one in a promotion command. However,
  1254. in the latter case, if shifting some line in the entry body
  1255. would alter document structure (e.g., insert a new headline),
  1256. indentation is not changed at all.
  1257. - Property drawers and planning information is inserted indented
  1258. when this variable is set. When nil, they will not be indented.
  1259. - TAB indents a line relative to current level. The lines below
  1260. a headline will be indented when this variable is set.
  1261. Note that this is all about true indentation, by adding and
  1262. removing space characters. See also `org-indent.el' which does
  1263. level-dependent indentation in a virtual way, i.e. at display
  1264. time in Emacs."
  1265. :group 'org-edit-structure
  1266. :type 'boolean)
  1267. (defcustom org-special-ctrl-a/e nil
  1268. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1269. When t, `C-a' will bring back the cursor to the beginning of the
  1270. headline text, i.e. after the stars and after a possible TODO
  1271. keyword. In an item, this will be the position after bullet and
  1272. check-box, if any. When the cursor is already at that position,
  1273. another `C-a' will bring it to the beginning of the line.
  1274. `C-e' will jump to the end of the headline, ignoring the presence
  1275. of tags in the headline. A second `C-e' will then jump to the
  1276. true end of the line, after any tags. This also means that, when
  1277. this variable is non-nil, `C-e' also will never jump beyond the
  1278. end of the heading of a folded section, i.e. not after the
  1279. ellipses.
  1280. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1281. normally, going to the true line boundary first. Only a directly
  1282. following, identical keypress will bring the cursor to the
  1283. special positions.
  1284. This may also be a cons cell where the behavior for `C-a' and
  1285. `C-e' is set separately."
  1286. :group 'org-edit-structure
  1287. :type '(choice
  1288. (const :tag "off" nil)
  1289. (const :tag "on: after stars/bullet and before tags first" t)
  1290. (const :tag "reversed: true line boundary first" reversed)
  1291. (cons :tag "Set C-a and C-e separately"
  1292. (choice :tag "Special C-a"
  1293. (const :tag "off" nil)
  1294. (const :tag "on: after stars/bullet first" t)
  1295. (const :tag "reversed: before stars/bullet first" reversed))
  1296. (choice :tag "Special C-e"
  1297. (const :tag "off" nil)
  1298. (const :tag "on: before tags first" t)
  1299. (const :tag "reversed: after tags first" reversed)))))
  1300. (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1301. (defcustom org-special-ctrl-k nil
  1302. "Non-nil means `C-k' will behave specially in headlines.
  1303. When nil, `C-k' will call the default `kill-line' command.
  1304. When t, the following will happen while the cursor is in the headline:
  1305. - When the cursor is at the beginning of a headline, kill the entire
  1306. line and possible the folded subtree below the line.
  1307. - When in the middle of the headline text, kill the headline up to the tags.
  1308. - When after the headline text, kill the tags."
  1309. :group 'org-edit-structure
  1310. :type 'boolean)
  1311. (defcustom org-ctrl-k-protect-subtree nil
  1312. "Non-nil means, do not delete a hidden subtree with C-k.
  1313. When set to the symbol `error', simply throw an error when C-k is
  1314. used to kill (part-of) a headline that has hidden text behind it.
  1315. Any other non-nil value will result in a query to the user, if it is
  1316. OK to kill that hidden subtree. When nil, kill without remorse."
  1317. :group 'org-edit-structure
  1318. :version "24.1"
  1319. :type '(choice
  1320. (const :tag "Do not protect hidden subtrees" nil)
  1321. (const :tag "Protect hidden subtrees with a security query" t)
  1322. (const :tag "Never kill a hidden subtree with C-k" error)))
  1323. (defcustom org-special-ctrl-o t
  1324. "Non-nil means, make `C-o' insert a row in tables."
  1325. :group 'org-edit-structure
  1326. :type 'boolean)
  1327. (defcustom org-catch-invisible-edits nil
  1328. "Check if in invisible region before inserting or deleting a character.
  1329. Valid values are:
  1330. nil Do not check, so just do invisible edits.
  1331. error Throw an error and do nothing.
  1332. show Make point visible, and do the requested edit.
  1333. show-and-error Make point visible, then throw an error and abort the edit.
  1334. smart Make point visible, and do insertion/deletion if it is
  1335. adjacent to visible text and the change feels predictable.
  1336. Never delete a previously invisible character or add in the
  1337. middle or right after an invisible region. Basically, this
  1338. allows insertion and backward-delete right before ellipses.
  1339. FIXME: maybe in this case we should not even show?"
  1340. :group 'org-edit-structure
  1341. :version "24.1"
  1342. :type '(choice
  1343. (const :tag "Do not check" nil)
  1344. (const :tag "Throw error when trying to edit" error)
  1345. (const :tag "Unhide, but do not do the edit" show-and-error)
  1346. (const :tag "Show invisible part and do the edit" show)
  1347. (const :tag "Be smart and do the right thing" smart)))
  1348. (defcustom org-yank-folded-subtrees t
  1349. "Non-nil means when yanking subtrees, fold them.
  1350. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1351. it starts with a heading and all other headings in it are either children
  1352. or siblings, then fold all the subtrees. However, do this only if no
  1353. text after the yank would be swallowed into a folded tree by this action."
  1354. :group 'org-edit-structure
  1355. :type 'boolean)
  1356. (defcustom org-yank-adjusted-subtrees nil
  1357. "Non-nil means when yanking subtrees, adjust the level.
  1358. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1359. this function for details."
  1360. :group 'org-edit-structure
  1361. :type 'boolean)
  1362. (defcustom org-M-RET-may-split-line '((default . t))
  1363. "Non-nil means M-RET will split the line at the cursor position.
  1364. When nil, it will go to the end of the line before making a
  1365. new line.
  1366. You may also set this option in a different way for different
  1367. contexts. Valid contexts are:
  1368. headline when creating a new headline
  1369. item when creating a new item
  1370. table in a table field
  1371. default the value to be used for all contexts not explicitly
  1372. customized"
  1373. :group 'org-structure
  1374. :group 'org-table
  1375. :type '(choice
  1376. (const :tag "Always" t)
  1377. (const :tag "Never" nil)
  1378. (repeat :greedy t :tag "Individual contexts"
  1379. (cons
  1380. (choice :tag "Context"
  1381. (const headline)
  1382. (const item)
  1383. (const table)
  1384. (const default))
  1385. (boolean)))))
  1386. (defcustom org-insert-heading-respect-content nil
  1387. "Non-nil means insert new headings after the current subtree.
  1388. When nil, the new heading is created directly after the current line.
  1389. The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
  1390. this variable on for the duration of the command."
  1391. :group 'org-structure
  1392. :type 'boolean)
  1393. (defcustom org-blank-before-new-entry '((heading . auto)
  1394. (plain-list-item . auto))
  1395. "Should `org-insert-heading' leave a blank line before new heading/item?
  1396. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1397. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1398. which case Org will look at the surrounding headings/items and try to
  1399. make an intelligent decision whether to insert a blank line or not."
  1400. :group 'org-edit-structure
  1401. :type '(list
  1402. (cons (const heading)
  1403. (choice (const :tag "Never" nil)
  1404. (const :tag "Always" t)
  1405. (const :tag "Auto" auto)))
  1406. (cons (const plain-list-item)
  1407. (choice (const :tag "Never" nil)
  1408. (const :tag "Always" t)
  1409. (const :tag "Auto" auto)))))
  1410. (defcustom org-insert-heading-hook nil
  1411. "Hook being run after inserting a new heading."
  1412. :group 'org-edit-structure
  1413. :type 'hook)
  1414. (defcustom org-enable-fixed-width-editor t
  1415. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1416. This currently only means they are never auto-wrapped.
  1417. When nil, such lines will be treated like ordinary lines."
  1418. :group 'org-edit-structure
  1419. :type 'boolean)
  1420. (defcustom org-goto-auto-isearch t
  1421. "Non-nil means typing characters in `org-goto' starts incremental search.
  1422. When nil, you can use these keybindings to navigate the buffer:
  1423. q Quit the org-goto interface
  1424. n Go to the next visible heading
  1425. p Go to the previous visible heading
  1426. f Go one heading forward on same level
  1427. b Go one heading backward on same level
  1428. u Go one heading up"
  1429. :group 'org-edit-structure
  1430. :type 'boolean)
  1431. (defgroup org-sparse-trees nil
  1432. "Options concerning sparse trees in Org-mode."
  1433. :tag "Org Sparse Trees"
  1434. :group 'org-structure)
  1435. (defcustom org-highlight-sparse-tree-matches t
  1436. "Non-nil means highlight all matches that define a sparse tree.
  1437. The highlights will automatically disappear the next time the buffer is
  1438. changed by an edit command."
  1439. :group 'org-sparse-trees
  1440. :type 'boolean)
  1441. (defcustom org-remove-highlights-with-change t
  1442. "Non-nil means any change to the buffer will remove temporary highlights.
  1443. \\<org-mode-map>\
  1444. Such highlights are created by `org-occur' and `org-clock-display'.
  1445. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1446. to get rid of the highlights.
  1447. The highlights created by `org-toggle-latex-fragment' always need
  1448. `\\[org-toggle-latex-fragment]' to be removed."
  1449. :group 'org-sparse-trees
  1450. :group 'org-time
  1451. :type 'boolean)
  1452. (defcustom org-occur-hook '(org-first-headline-recenter)
  1453. "Hook that is run after `org-occur' has constructed a sparse tree.
  1454. This can be used to recenter the window to show as much of the structure
  1455. as possible."
  1456. :group 'org-sparse-trees
  1457. :type 'hook)
  1458. (defgroup org-imenu-and-speedbar nil
  1459. "Options concerning imenu and speedbar in Org-mode."
  1460. :tag "Org Imenu and Speedbar"
  1461. :group 'org-structure)
  1462. (defcustom org-imenu-depth 2
  1463. "The maximum level for Imenu access to Org-mode headlines.
  1464. This also applied for speedbar access."
  1465. :group 'org-imenu-and-speedbar
  1466. :type 'integer)
  1467. (defgroup org-table nil
  1468. "Options concerning tables in Org-mode."
  1469. :tag "Org Table"
  1470. :group 'org)
  1471. (defcustom org-enable-table-editor 'optimized
  1472. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1473. When nil, such lines will be treated like ordinary lines.
  1474. When equal to the symbol `optimized', the table editor will be optimized to
  1475. do the following:
  1476. - Automatic overwrite mode in front of whitespace in table fields.
  1477. This makes the structure of the table stay in tact as long as the edited
  1478. field does not exceed the column width.
  1479. - Minimize the number of realigns. Normally, the table is aligned each time
  1480. TAB or RET are pressed to move to another field. With optimization this
  1481. happens only if changes to a field might have changed the column width.
  1482. Optimization requires replacing the functions `self-insert-command',
  1483. `delete-char', and `backward-delete-char' in Org-mode buffers, with a
  1484. slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
  1485. very good at guessing when a re-align will be necessary, but you can always
  1486. force one with \\[org-ctrl-c-ctrl-c].
  1487. If you would like to use the optimized version in Org-mode, but the
  1488. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1489. This variable can be used to turn on and off the table editor during a session,
  1490. but in order to toggle optimization, a restart is required.
  1491. See also the variable `org-table-auto-blank-field'."
  1492. :group 'org-table
  1493. :type '(choice
  1494. (const :tag "off" nil)
  1495. (const :tag "on" t)
  1496. (const :tag "on, optimized" optimized)))
  1497. (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
  1498. (version<= emacs-version "24.1"))
  1499. "Non-nil means cluster self-insert commands for undo when possible.
  1500. If this is set, then, like in the Emacs command loop, 20 consecutive
  1501. characters will be undone together.
  1502. This is configurable, because there is some impact on typing performance."
  1503. :group 'org-table
  1504. :type 'boolean)
  1505. (defcustom org-table-tab-recognizes-table.el t
  1506. "Non-nil means TAB will automatically notice a table.el table.
  1507. When it sees such a table, it moves point into it and - if necessary -
  1508. calls `table-recognize-table'."
  1509. :group 'org-table-editing
  1510. :type 'boolean)
  1511. (defgroup org-link nil
  1512. "Options concerning links in Org-mode."
  1513. :tag "Org Link"
  1514. :group 'org)
  1515. (defvar-local org-link-abbrev-alist-local nil
  1516. "Buffer-local version of `org-link-abbrev-alist', which see.
  1517. The value of this is taken from the #+LINK lines.")
  1518. (defcustom org-link-abbrev-alist nil
  1519. "Alist of link abbreviations.
  1520. The car of each element is a string, to be replaced at the start of a link.
  1521. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1522. links in Org-mode buffers can have an optional tag after a double colon, e.g.
  1523. [[linkkey:tag][description]]
  1524. The `linkkey' must be a word word, starting with a letter, followed
  1525. by letters, numbers, `-' or `_'.
  1526. If REPLACE is a string, the tag will simply be appended to create the link.
  1527. If the string contains \"%s\", the tag will be inserted there. If the string
  1528. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1529. at that point (see the function `url-hexify-string'). If the string contains
  1530. the specifier \"%(my-function)\", then the custom function `my-function' will
  1531. be invoked: this function takes the tag as its only argument and must return
  1532. a string.
  1533. REPLACE may also be a function that will be called with the tag as the
  1534. only argument to create the link, which should be returned as a string.
  1535. See the manual for examples."
  1536. :group 'org-link
  1537. :type '(repeat
  1538. (cons
  1539. (string :tag "Protocol")
  1540. (choice
  1541. (string :tag "Format")
  1542. (function)))))
  1543. (defcustom org-descriptive-links t
  1544. "Non-nil means Org will display descriptive links.
  1545. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1546. \"Org Website\", hiding the link itself and just displaying its
  1547. description. When set to nil, Org will display the full links
  1548. literally.
  1549. You can interactively set the value of this variable by calling
  1550. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1551. :group 'org-link
  1552. :type 'boolean)
  1553. (defcustom org-link-file-path-type 'adaptive
  1554. "How the path name in file links should be stored.
  1555. Valid values are:
  1556. relative Relative to the current directory, i.e. the directory of the file
  1557. into which the link is being inserted.
  1558. absolute Absolute path, if possible with ~ for home directory.
  1559. noabbrev Absolute path, no abbreviation of home directory.
  1560. adaptive Use relative path for files in the current directory and sub-
  1561. directories of it. For other files, use an absolute path."
  1562. :group 'org-link
  1563. :type '(choice
  1564. (const relative)
  1565. (const absolute)
  1566. (const noabbrev)
  1567. (const adaptive)))
  1568. (defvaralias 'org-activate-links 'org-highlight-links)
  1569. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1570. "Types of links that should be highlighted in Org-mode files.
  1571. This is a list of symbols, each one of them leading to the
  1572. highlighting of a certain link type.
  1573. You can still open links that are not highlighted.
  1574. In principle, it does not hurt to turn on highlighting for all
  1575. link types. There may be a small gain when turning off unused
  1576. link types. The types are:
  1577. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1578. angle Links in angular brackets that may contain whitespace like
  1579. <bbdb:Carsten Dominik>.
  1580. plain Plain links in normal text, no whitespace, like http://google.com.
  1581. radio Text that is matched by a radio target, see manual for details.
  1582. tag Tag settings in a headline (link to tag search).
  1583. date Time stamps (link to calendar).
  1584. footnote Footnote labels.
  1585. If you set this variable during an Emacs session, use `org-mode-restart'
  1586. in the Org buffer so that the change takes effect."
  1587. :group 'org-link
  1588. :group 'org-appearance
  1589. :type '(set :greedy t
  1590. (const :tag "Double bracket links" bracket)
  1591. (const :tag "Angular bracket links" angle)
  1592. (const :tag "Plain text links" plain)
  1593. (const :tag "Radio target matches" radio)
  1594. (const :tag "Tags" tag)
  1595. (const :tag "Timestamps" date)
  1596. (const :tag "Footnotes" footnote)))
  1597. (defcustom org-make-link-description-function nil
  1598. "Function to use for generating link descriptions from links.
  1599. When nil, the link location will be used. This function must take
  1600. two parameters: the first one is the link, the second one is the
  1601. description generated by `org-insert-link'. The function should
  1602. return the description to use."
  1603. :group 'org-link
  1604. :type '(choice (const nil) (function)))
  1605. (defgroup org-link-store nil
  1606. "Options concerning storing links in Org-mode."
  1607. :tag "Org Store Link"
  1608. :group 'org-link)
  1609. (defcustom org-url-hexify-p t
  1610. "When non-nil, hexify URL when creating a link."
  1611. :type 'boolean
  1612. :version "24.3"
  1613. :group 'org-link-store)
  1614. (defcustom org-email-link-description-format "Email %c: %.30s"
  1615. "Format of the description part of a link to an email or usenet message.
  1616. The following %-escapes will be replaced by corresponding information:
  1617. %F full \"From\" field
  1618. %f name, taken from \"From\" field, address if no name
  1619. %T full \"To\" field
  1620. %t first name in \"To\" field, address if no name
  1621. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1622. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1623. %s subject
  1624. %d date
  1625. %m message-id.
  1626. You may use normal field width specification between the % and the letter.
  1627. This is for example useful to limit the length of the subject.
  1628. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1629. :group 'org-link-store
  1630. :type 'string)
  1631. (defcustom org-from-is-user-regexp
  1632. (let (r1 r2)
  1633. (when (and user-mail-address (not (string= user-mail-address "")))
  1634. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1635. (when (and user-full-name (not (string= user-full-name "")))
  1636. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1637. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1638. "Regexp matched against the \"From:\" header of an email or usenet message.
  1639. It should match if the message is from the user him/herself."
  1640. :group 'org-link-store
  1641. :type 'regexp)
  1642. (defcustom org-context-in-file-links t
  1643. "Non-nil means file links from `org-store-link' contain context.
  1644. A search string will be added to the file name with :: as separator and
  1645. used to find the context when the link is activated by the command
  1646. `org-open-at-point'. When this option is t, the entire active region
  1647. will be placed in the search string of the file link. If set to a
  1648. positive integer, only the first n lines of context will be stored.
  1649. Using a prefix arg to the command \\[org-store-link] (`org-store-link')
  1650. negates this setting for the duration of the command."
  1651. :group 'org-link-store
  1652. :type '(choice boolean integer))
  1653. (defcustom org-keep-stored-link-after-insertion nil
  1654. "Non-nil means keep link in list for entire session.
  1655. The command `org-store-link' adds a link pointing to the current
  1656. location to an internal list. These links accumulate during a session.
  1657. The command `org-insert-link' can be used to insert links into any
  1658. Org-mode file (offering completion for all stored links). When this
  1659. option is nil, every link which has been inserted once using \\[org-insert-link]
  1660. will be removed from the list, to make completing the unused links
  1661. more efficient."
  1662. :group 'org-link-store
  1663. :type 'boolean)
  1664. (defgroup org-link-follow nil
  1665. "Options concerning following links in Org-mode."
  1666. :tag "Org Follow Link"
  1667. :group 'org-link)
  1668. (defcustom org-link-translation-function nil
  1669. "Function to translate links with different syntax to Org syntax.
  1670. This can be used to translate links created for example by the Planner
  1671. or emacs-wiki packages to Org syntax.
  1672. The function must accept two parameters, a TYPE containing the link
  1673. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1674. which is everything after the link protocol. It should return a cons
  1675. with possibly modified values of type and path.
  1676. Org contains a function for this, so if you set this variable to
  1677. `org-translate-link-from-planner', you should be able follow many
  1678. links created by planner."
  1679. :group 'org-link-follow
  1680. :type '(choice (const nil) (function)))
  1681. (defcustom org-follow-link-hook nil
  1682. "Hook that is run after a link has been followed."
  1683. :group 'org-link-follow
  1684. :type 'hook)
  1685. (defcustom org-tab-follows-link nil
  1686. "Non-nil means on links TAB will follow the link.
  1687. Needs to be set before org.el is loaded.
  1688. This really should not be used, it does not make sense, and the
  1689. implementation is bad."
  1690. :group 'org-link-follow
  1691. :type 'boolean)
  1692. (defcustom org-return-follows-link nil
  1693. "Non-nil means on links RET will follow the link.
  1694. In tables, the special behavior of RET has precedence."
  1695. :group 'org-link-follow
  1696. :type 'boolean)
  1697. (defcustom org-mouse-1-follows-link
  1698. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1699. "Non-nil means mouse-1 on a link will follow the link.
  1700. A longer mouse click will still set point. Does not work on XEmacs.
  1701. Needs to be set before org.el is loaded."
  1702. :group 'org-link-follow
  1703. :version "24.4"
  1704. :package-version '(Org . "8.3")
  1705. :type '(choice
  1706. (const :tag "A double click follows the link" double)
  1707. (const :tag "Unconditionally follow the link with mouse-1" t)
  1708. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1709. (defcustom org-mark-ring-length 4
  1710. "Number of different positions to be recorded in the ring.
  1711. Changing this requires a restart of Emacs to work correctly."
  1712. :group 'org-link-follow
  1713. :type 'integer)
  1714. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1715. "Non-nil means internal links in Org files must exactly match a headline.
  1716. When nil, the link search tries to match a phrase with all words
  1717. in the search text."
  1718. :group 'org-link-follow
  1719. :version "24.1"
  1720. :type '(choice
  1721. (const :tag "Use fuzzy text search" nil)
  1722. (const :tag "Match only exact headline" t)
  1723. (const :tag "Match exact headline or query to create it"
  1724. query-to-create)))
  1725. (defcustom org-link-frame-setup
  1726. '((vm . vm-visit-folder-other-frame)
  1727. (vm-imap . vm-visit-imap-folder-other-frame)
  1728. (gnus . org-gnus-no-new-news)
  1729. (file . find-file-other-window)
  1730. (wl . wl-other-frame))
  1731. "Setup the frame configuration for following links.
  1732. When following a link with Emacs, it may often be useful to display
  1733. this link in another window or frame. This variable can be used to
  1734. set this up for the different types of links.
  1735. For VM, use any of
  1736. `vm-visit-folder'
  1737. `vm-visit-folder-other-window'
  1738. `vm-visit-folder-other-frame'
  1739. For Gnus, use any of
  1740. `gnus'
  1741. `gnus-other-frame'
  1742. `org-gnus-no-new-news'
  1743. For FILE, use any of
  1744. `find-file'
  1745. `find-file-other-window'
  1746. `find-file-other-frame'
  1747. For Wanderlust use any of
  1748. `wl'
  1749. `wl-other-frame'
  1750. For the calendar, use the variable `calendar-setup'.
  1751. For BBDB, it is currently only possible to display the matches in
  1752. another window."
  1753. :group 'org-link-follow
  1754. :type '(list
  1755. (cons (const vm)
  1756. (choice
  1757. (const vm-visit-folder)
  1758. (const vm-visit-folder-other-window)
  1759. (const vm-visit-folder-other-frame)))
  1760. (cons (const vm-imap)
  1761. (choice
  1762. (const vm-visit-imap-folder)
  1763. (const vm-visit-imap-folder-other-window)
  1764. (const vm-visit-imap-folder-other-frame)))
  1765. (cons (const gnus)
  1766. (choice
  1767. (const gnus)
  1768. (const gnus-other-frame)
  1769. (const org-gnus-no-new-news)))
  1770. (cons (const file)
  1771. (choice
  1772. (const find-file)
  1773. (const find-file-other-window)
  1774. (const find-file-other-frame)))
  1775. (cons (const wl)
  1776. (choice
  1777. (const wl)
  1778. (const wl-other-frame)))))
  1779. (defcustom org-display-internal-link-with-indirect-buffer nil
  1780. "Non-nil means use indirect buffer to display infile links.
  1781. Activating internal links (from one location in a file to another location
  1782. in the same file) normally just jumps to the location. When the link is
  1783. activated with a \\[universal-argument] prefix (or with mouse-3), the link \
  1784. is displayed in
  1785. another window. When this option is set, the other window actually displays
  1786. an indirect buffer clone of the current buffer, to avoid any visibility
  1787. changes to the current buffer."
  1788. :group 'org-link-follow
  1789. :type 'boolean)
  1790. (defcustom org-open-non-existing-files nil
  1791. "Non-nil means `org-open-file' will open non-existing files.
  1792. When nil, an error will be generated.
  1793. This variable applies only to external applications because they
  1794. might choke on non-existing files. If the link is to a file that
  1795. will be opened in Emacs, the variable is ignored."
  1796. :group 'org-link-follow
  1797. :type 'boolean)
  1798. (defcustom org-open-directory-means-index-dot-org nil
  1799. "Non-nil means a link to a directory really means to index.org.
  1800. When nil, following a directory link will run dired or open a finder/explorer
  1801. window on that directory."
  1802. :group 'org-link-follow
  1803. :type 'boolean)
  1804. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1805. "Non-nil means ask for confirmation before executing shell links.
  1806. Shell links can be dangerous: just think about a link
  1807. [[shell:rm -rf ~/*][Google Search]]
  1808. This link would show up in your Org-mode document as \"Google Search\",
  1809. but really it would remove your entire home directory.
  1810. Therefore we advise against setting this variable to nil.
  1811. Just change it to `y-or-n-p' if you want to confirm with a
  1812. single keystroke rather than having to type \"yes\"."
  1813. :group 'org-link-follow
  1814. :type '(choice
  1815. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1816. (const :tag "with y-or-n (faster)" y-or-n-p)
  1817. (const :tag "no confirmation (dangerous)" nil)))
  1818. (put 'org-confirm-shell-link-function
  1819. 'safe-local-variable
  1820. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1821. (defcustom org-confirm-shell-link-not-regexp ""
  1822. "A regexp to skip confirmation for shell links."
  1823. :group 'org-link-follow
  1824. :version "24.1"
  1825. :type 'regexp)
  1826. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1827. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1828. Elisp links can be dangerous: just think about a link
  1829. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1830. This link would show up in your Org-mode document as \"Google Search\",
  1831. but really it would remove your entire home directory.
  1832. Therefore we advise against setting this variable to nil.
  1833. Just change it to `y-or-n-p' if you want to confirm with a
  1834. single keystroke rather than having to type \"yes\"."
  1835. :group 'org-link-follow
  1836. :type '(choice
  1837. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1838. (const :tag "with y-or-n (faster)" y-or-n-p)
  1839. (const :tag "no confirmation (dangerous)" nil)))
  1840. (put 'org-confirm-shell-link-function
  1841. 'safe-local-variable
  1842. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1843. (defcustom org-confirm-elisp-link-not-regexp ""
  1844. "A regexp to skip confirmation for Elisp links."
  1845. :group 'org-link-follow
  1846. :version "24.1"
  1847. :type 'regexp)
  1848. (defconst org-file-apps-defaults-gnu
  1849. '((remote . emacs)
  1850. (system . mailcap)
  1851. (t . mailcap))
  1852. "Default file applications on a UNIX or GNU/Linux system.
  1853. See `org-file-apps'.")
  1854. (defconst org-file-apps-defaults-macosx
  1855. '((remote . emacs)
  1856. (t . "open %s")
  1857. (system . "open %s")
  1858. ("ps.gz" . "gv %s")
  1859. ("eps.gz" . "gv %s")
  1860. ("dvi" . "xdvi %s")
  1861. ("fig" . "xfig %s"))
  1862. "Default file applications on a MacOS X system.
  1863. The system \"open\" is known as a default, but we use X11 applications
  1864. for some files for which the OS does not have a good default.
  1865. See `org-file-apps'.")
  1866. (defconst org-file-apps-defaults-windowsnt
  1867. (list
  1868. '(remote . emacs)
  1869. (cons t
  1870. (list (if (featurep 'xemacs)
  1871. 'mswindows-shell-execute
  1872. 'w32-shell-execute)
  1873. "open" 'file))
  1874. (cons 'system
  1875. (list (if (featurep 'xemacs)
  1876. 'mswindows-shell-execute
  1877. 'w32-shell-execute)
  1878. "open" 'file)))
  1879. "Default file applications on a Windows NT system.
  1880. The system \"open\" is used for most files.
  1881. See `org-file-apps'.")
  1882. (defcustom org-file-apps
  1883. '((auto-mode . emacs)
  1884. ("\\.mm\\'" . default)
  1885. ("\\.x?html?\\'" . default)
  1886. ("\\.pdf\\'" . default))
  1887. "External applications for opening `file:path' items in a document.
  1888. Org-mode uses system defaults for different file types, but
  1889. you can use this variable to set the application for a given file
  1890. extension. The entries in this list are cons cells where the car identifies
  1891. files and the cdr the corresponding command. Possible values for the
  1892. file identifier are
  1893. \"string\" A string as a file identifier can be interpreted in different
  1894. ways, depending on its contents:
  1895. - Alphanumeric characters only:
  1896. Match links with this file extension.
  1897. Example: (\"pdf\" . \"evince %s\")
  1898. to open PDFs with evince.
  1899. - Regular expression: Match links where the
  1900. filename matches the regexp. If you want to
  1901. use groups here, use shy groups.
  1902. Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
  1903. (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
  1904. to open *.html and *.xhtml with firefox.
  1905. - Regular expression which contains (non-shy) groups:
  1906. Match links where the whole link, including \"::\", and
  1907. anything after that, matches the regexp.
  1908. In a custom command string, %1, %2, etc. are replaced with
  1909. the parts of the link that were matched by the groups.
  1910. For backwards compatibility, if a command string is given
  1911. that does not use any of the group matches, this case is
  1912. handled identically to the second one (i.e. match against
  1913. file name only).
  1914. In a custom lisp form, you can access the group matches with
  1915. (match-string n link).
  1916. Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
  1917. to open [[file:document.pdf::5]] with evince at page 5.
  1918. `directory' Matches a directory
  1919. `remote' Matches a remote file, accessible through tramp or efs.
  1920. Remote files most likely should be visited through Emacs
  1921. because external applications cannot handle such paths.
  1922. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1923. so all files Emacs knows how to handle. Using this with
  1924. command `emacs' will open most files in Emacs. Beware that this
  1925. will also open html files inside Emacs, unless you add
  1926. (\"html\" . default) to the list as well.
  1927. t Default for files not matched by any of the other options.
  1928. `system' The system command to open files, like `open' on Windows
  1929. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1930. that will be selected if you call `C-c C-o' with a double
  1931. \\[universal-argument] \\[universal-argument] prefix.
  1932. Possible values for the command are:
  1933. `emacs' The file will be visited by the current Emacs process.
  1934. `default' Use the default application for this file type, which is the
  1935. association for t in the list, most likely in the system-specific
  1936. part.
  1937. This can be used to overrule an unwanted setting in the
  1938. system-specific variable.
  1939. `system' Use the system command for opening files, like \"open\".
  1940. This command is specified by the entry whose car is `system'.
  1941. Most likely, the system-specific version of this variable
  1942. does define this command, but you can overrule/replace it
  1943. here.
  1944. string A command to be executed by a shell; %s will be replaced
  1945. by the path to the file.
  1946. sexp A Lisp form which will be evaluated. The file path will
  1947. be available in the Lisp variable `file'.
  1948. For more examples, see the system specific constants
  1949. `org-file-apps-defaults-macosx'
  1950. `org-file-apps-defaults-windowsnt'
  1951. `org-file-apps-defaults-gnu'."
  1952. :group 'org-link-follow
  1953. :type '(repeat
  1954. (cons (choice :value ""
  1955. (string :tag "Extension")
  1956. (const :tag "System command to open files" system)
  1957. (const :tag "Default for unrecognized files" t)
  1958. (const :tag "Remote file" remote)
  1959. (const :tag "Links to a directory" directory)
  1960. (const :tag "Any files that have Emacs modes"
  1961. auto-mode))
  1962. (choice :value ""
  1963. (const :tag "Visit with Emacs" emacs)
  1964. (const :tag "Use default" default)
  1965. (const :tag "Use the system command" system)
  1966. (string :tag "Command")
  1967. (sexp :tag "Lisp form")))))
  1968. (defcustom org-doi-server-url "http://dx.doi.org/"
  1969. "The URL of the DOI server."
  1970. :type 'string
  1971. :version "24.3"
  1972. :group 'org-link-follow)
  1973. (defgroup org-refile nil
  1974. "Options concerning refiling entries in Org-mode."
  1975. :tag "Org Refile"
  1976. :group 'org)
  1977. (defcustom org-directory "~/org"
  1978. "Directory with org files.
  1979. This is just a default location to look for Org files. There is no need
  1980. at all to put your files into this directory. It is only used in the
  1981. following situations:
  1982. 1. When a capture template specifies a target file that is not an
  1983. absolute path. The path will then be interpreted relative to
  1984. `org-directory'
  1985. 2. When a capture note is filed away in an interactive way (when exiting the
  1986. note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
  1987. with `org-directory' as the default path."
  1988. :group 'org-refile
  1989. :group 'org-capture
  1990. :type 'directory)
  1991. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1992. "Default target for storing notes.
  1993. Used as a fall back file for org-capture.el, for templates that
  1994. do not specify a target file."
  1995. :group 'org-refile
  1996. :group 'org-capture
  1997. :type 'file)
  1998. (defcustom org-goto-interface 'outline
  1999. "The default interface to be used for `org-goto'.
  2000. Allowed values are:
  2001. outline The interface shows an outline of the relevant file
  2002. and the correct heading is found by moving through
  2003. the outline or by searching with incremental search.
  2004. outline-path-completion Headlines in the current buffer are offered via
  2005. completion. This is the interface also used by
  2006. the refile command."
  2007. :group 'org-refile
  2008. :type '(choice
  2009. (const :tag "Outline" outline)
  2010. (const :tag "Outline-path-completion" outline-path-completion)))
  2011. (defcustom org-goto-max-level 5
  2012. "Maximum target level when running `org-goto' with refile interface."
  2013. :group 'org-refile
  2014. :type 'integer)
  2015. (defcustom org-reverse-note-order nil
  2016. "Non-nil means store new notes at the beginning of a file or entry.
  2017. When nil, new notes will be filed to the end of a file or entry.
  2018. This can also be a list with cons cells of regular expressions that
  2019. are matched against file names, and values."
  2020. :group 'org-capture
  2021. :group 'org-refile
  2022. :type '(choice
  2023. (const :tag "Reverse always" t)
  2024. (const :tag "Reverse never" nil)
  2025. (repeat :tag "By file name regexp"
  2026. (cons regexp boolean))))
  2027. (defcustom org-log-refile nil
  2028. "Information to record when a task is refiled.
  2029. Possible values are:
  2030. nil Don't add anything
  2031. time Add a time stamp to the task
  2032. note Prompt for a note and add it with template `org-log-note-headings'
  2033. This option can also be set with on a per-file-basis with
  2034. #+STARTUP: nologrefile
  2035. #+STARTUP: logrefile
  2036. #+STARTUP: lognoterefile
  2037. You can have local logging settings for a subtree by setting the LOGGING
  2038. property to one or more of these keywords.
  2039. When bulk-refiling from the agenda, the value `note' is forbidden and
  2040. will temporarily be changed to `time'."
  2041. :group 'org-refile
  2042. :group 'org-progress
  2043. :version "24.1"
  2044. :type '(choice
  2045. (const :tag "No logging" nil)
  2046. (const :tag "Record timestamp" time)
  2047. (const :tag "Record timestamp with note." note)))
  2048. (defcustom org-refile-targets nil
  2049. "Targets for refiling entries with \\[org-refile].
  2050. This is a list of cons cells. Each cell contains:
  2051. - a specification of the files to be considered, either a list of files,
  2052. or a symbol whose function or variable value will be used to retrieve
  2053. a file name or a list of file names. If you use `org-agenda-files' for
  2054. that, all agenda files will be scanned for targets. Nil means consider
  2055. headings in the current buffer.
  2056. - A specification of how to find candidate refile targets. This may be
  2057. any of:
  2058. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2059. This tag has to be present in all target headlines, inheritance will
  2060. not be considered.
  2061. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2062. todo keyword.
  2063. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2064. headlines that are refiling targets.
  2065. - a cons cell (:level . N). Any headline of level N is considered a target.
  2066. Note that, when `org-odd-levels-only' is set, level corresponds to
  2067. order in hierarchy, not to the number of stars.
  2068. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2069. Note that, when `org-odd-levels-only' is set, level corresponds to
  2070. order in hierarchy, not to the number of stars.
  2071. Each element of this list generates a set of possible targets.
  2072. The union of these sets is presented (with completion) to
  2073. the user by `org-refile'.
  2074. You can set the variable `org-refile-target-verify-function' to a function
  2075. to verify each headline found by the simple criteria above.
  2076. When this variable is nil, all top-level headlines in the current buffer
  2077. are used, equivalent to the value `((nil . (:level . 1))'."
  2078. :group 'org-refile
  2079. :type '(repeat
  2080. (cons
  2081. (choice :value org-agenda-files
  2082. (const :tag "All agenda files" org-agenda-files)
  2083. (const :tag "Current buffer" nil)
  2084. (function) (variable) (file))
  2085. (choice :tag "Identify target headline by"
  2086. (cons :tag "Specific tag" (const :value :tag) (string))
  2087. (cons :tag "TODO keyword" (const :value :todo) (string))
  2088. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2089. (cons :tag "Level number" (const :value :level) (integer))
  2090. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2091. (defcustom org-refile-target-verify-function nil
  2092. "Function to verify if the headline at point should be a refile target.
  2093. The function will be called without arguments, with point at the
  2094. beginning of the headline. It should return t and leave point
  2095. where it is if the headline is a valid target for refiling.
  2096. If the target should not be selected, the function must return nil.
  2097. In addition to this, it may move point to a place from where the search
  2098. should be continued. For example, the function may decide that the entire
  2099. subtree of the current entry should be excluded and move point to the end
  2100. of the subtree."
  2101. :group 'org-refile
  2102. :type '(choice
  2103. (const nil)
  2104. (function)))
  2105. (defcustom org-refile-use-cache nil
  2106. "Non-nil means cache refile targets to speed up the process.
  2107. \\<org-mode-map>\
  2108. The cache for a particular file will be updated automatically when
  2109. the buffer has been killed, or when any of the marker used for flagging
  2110. refile targets no longer points at a live buffer.
  2111. If you have added new entries to a buffer that might themselves be targets,
  2112. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2113. if you find that easier, \
  2114. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2115. \\[org-refile]'."
  2116. :group 'org-refile
  2117. :version "24.1"
  2118. :type 'boolean)
  2119. (defcustom org-refile-use-outline-path nil
  2120. "Non-nil means provide refile targets as paths.
  2121. So a level 3 headline will be available as level1/level2/level3.
  2122. When the value is `file', also include the file name (without directory)
  2123. into the path. In this case, you can also stop the completion after
  2124. the file name, to get entries inserted as top level in the file.
  2125. When `full-file-path', include the full file path."
  2126. :group 'org-refile
  2127. :type '(choice
  2128. (const :tag "Not" nil)
  2129. (const :tag "Yes" t)
  2130. (const :tag "Start with file name" file)
  2131. (const :tag "Start with full file path" full-file-path)))
  2132. (defcustom org-outline-path-complete-in-steps t
  2133. "Non-nil means complete the outline path in hierarchical steps.
  2134. When Org-mode uses the refile interface to select an outline path
  2135. \(see variable `org-refile-use-outline-path'), the completion of
  2136. the path can be done in a single go, or it can be done in steps down
  2137. the headline hierarchy. Going in steps is probably the best if you
  2138. do not use a special completion package like `ido' or `icicles'.
  2139. However, when using these packages, going in one step can be very
  2140. fast, while still showing the whole path to the entry."
  2141. :group 'org-refile
  2142. :type 'boolean)
  2143. (defcustom org-refile-allow-creating-parent-nodes nil
  2144. "Non-nil means allow to create new nodes as refile targets.
  2145. New nodes are then created by adding \"/new node name\" to the completion
  2146. of an existing node. When the value of this variable is `confirm',
  2147. new node creation must be confirmed by the user (recommended).
  2148. When nil, the completion must match an existing entry.
  2149. Note that, if the new heading is not seen by the criteria
  2150. listed in `org-refile-targets', multiple instances of the same
  2151. heading would be created by trying again to file under the new
  2152. heading."
  2153. :group 'org-refile
  2154. :type '(choice
  2155. (const :tag "Never" nil)
  2156. (const :tag "Always" t)
  2157. (const :tag "Prompt for confirmation" confirm)))
  2158. (defcustom org-refile-active-region-within-subtree nil
  2159. "Non-nil means also refile active region within a subtree.
  2160. By default `org-refile' doesn't allow refiling regions if they
  2161. don't contain a set of subtrees, but it might be convenient to
  2162. do so sometimes: in that case, the first line of the region is
  2163. converted to a headline before refiling."
  2164. :group 'org-refile
  2165. :version "24.1"
  2166. :type 'boolean)
  2167. (defgroup org-todo nil
  2168. "Options concerning TODO items in Org-mode."
  2169. :tag "Org TODO"
  2170. :group 'org)
  2171. (defgroup org-progress nil
  2172. "Options concerning Progress logging in Org-mode."
  2173. :tag "Org Progress"
  2174. :group 'org-time)
  2175. (defvar org-todo-interpretation-widgets
  2176. '((:tag "Sequence (cycling hits every state)" sequence)
  2177. (:tag "Type (cycling directly to DONE)" type))
  2178. "The available interpretation symbols for customizing `org-todo-keywords'.
  2179. Interested libraries should add to this list.")
  2180. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2181. "List of TODO entry keyword sequences and their interpretation.
  2182. \\<org-mode-map>This is a list of sequences.
  2183. Each sequence starts with a symbol, either `sequence' or `type',
  2184. indicating if the keywords should be interpreted as a sequence of
  2185. action steps, or as different types of TODO items. The first
  2186. keywords are states requiring action - these states will select a headline
  2187. for inclusion into the global TODO list Org-mode produces. If one of
  2188. the \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2189. signify that no further action is necessary. If \"|\" is not found,
  2190. the last keyword is treated as the only DONE state of the sequence.
  2191. The command \\[org-todo] cycles an entry through these states, and one
  2192. additional state where no keyword is present. For details about this
  2193. cycling, see the manual.
  2194. TODO keywords and interpretation can also be set on a per-file basis with
  2195. the special #+SEQ_TODO and #+TYP_TODO lines.
  2196. Each keyword can optionally specify a character for fast state selection
  2197. \(in combination with the variable `org-use-fast-todo-selection')
  2198. and specifiers for state change logging, using the same syntax that
  2199. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2200. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2201. indicates to record a time stamp each time this state is selected.
  2202. Each keyword may also specify if a timestamp or a note should be
  2203. recorded when entering or leaving the state, by adding additional
  2204. characters in the parenthesis after the keyword. This looks like this:
  2205. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2206. record only the time of the state change. With X and Y being either
  2207. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2208. Y when leaving the state if and only if the *target* state does not
  2209. define X. You may omit any of the fast-selection key or X or /Y,
  2210. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2211. For backward compatibility, this variable may also be just a list
  2212. of keywords. In this case the interpretation (sequence or type) will be
  2213. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2214. :group 'org-todo
  2215. :group 'org-keywords
  2216. :type '(choice
  2217. (repeat :tag "Old syntax, just keywords"
  2218. (string :tag "Keyword"))
  2219. (repeat :tag "New syntax"
  2220. (cons
  2221. (choice
  2222. :tag "Interpretation"
  2223. ;;Quick and dirty way to see
  2224. ;;`org-todo-interpretations'. This takes the
  2225. ;;place of item arguments
  2226. :convert-widget
  2227. (lambda (widget)
  2228. (widget-put widget
  2229. :args (mapcar
  2230. (lambda (x)
  2231. (widget-convert
  2232. (cons 'const x)))
  2233. org-todo-interpretation-widgets))
  2234. widget))
  2235. (repeat
  2236. (string :tag "Keyword"))))))
  2237. (defvar-local org-todo-keywords-1 nil
  2238. "All TODO and DONE keywords active in a buffer.")
  2239. (defvar org-todo-keywords-for-agenda nil)
  2240. (defvar org-done-keywords-for-agenda nil)
  2241. (defvar org-todo-keyword-alist-for-agenda nil)
  2242. (defvar org-tag-alist-for-agenda nil
  2243. "Alist of all tags from all agenda files.")
  2244. (defvar org-tag-groups-alist-for-agenda nil
  2245. "Alist of all groups tags from all current agenda files.")
  2246. (defvar-local org-tag-groups-alist nil)
  2247. (defvar org-agenda-contributing-files nil)
  2248. (defvar-local org-not-done-keywords nil)
  2249. (defvar-local org-done-keywords nil)
  2250. (defvar-local org-todo-heads nil)
  2251. (defvar-local org-todo-sets nil)
  2252. (defvar-local org-todo-log-states nil)
  2253. (defvar-local org-todo-kwd-alist nil)
  2254. (defvar-local org-todo-key-alist nil)
  2255. (defvar-local org-todo-key-trigger nil)
  2256. (defcustom org-todo-interpretation 'sequence
  2257. "Controls how TODO keywords are interpreted.
  2258. This variable is in principle obsolete and is only used for
  2259. backward compatibility, if the interpretation of todo keywords is
  2260. not given already in `org-todo-keywords'. See that variable for
  2261. more information."
  2262. :group 'org-todo
  2263. :group 'org-keywords
  2264. :type '(choice (const sequence)
  2265. (const type)))
  2266. (defcustom org-use-fast-todo-selection t
  2267. "\\<org-mode-map>\
  2268. Non-nil means use the fast todo selection scheme with \\[org-todo].
  2269. This variable describes if and under what circumstances the cycling
  2270. mechanism for TODO keywords will be replaced by a single-key, direct
  2271. selection scheme.
  2272. When nil, fast selection is never used.
  2273. When the symbol `prefix', it will be used when `org-todo' is called
  2274. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2275. in an Org-mode buffer, and
  2276. `\\[universal-argument] t' in an agenda buffer.
  2277. When t, fast selection is used by default. In this case, the prefix
  2278. argument forces cycling instead.
  2279. In all cases, the special interface is only used if access keys have
  2280. actually been assigned by the user, i.e. if keywords in the configuration
  2281. are followed by a letter in parenthesis, like TODO(t)."
  2282. :group 'org-todo
  2283. :type '(choice
  2284. (const :tag "Never" nil)
  2285. (const :tag "By default" t)
  2286. (const :tag "Only with C-u C-c C-t" prefix)))
  2287. (defcustom org-provide-todo-statistics t
  2288. "Non-nil means update todo statistics after insert and toggle.
  2289. ALL-HEADLINES means update todo statistics by including headlines
  2290. with no TODO keyword as well, counting them as not done.
  2291. A list of TODO keywords means the same, but skip keywords that are
  2292. not in this list.
  2293. When set to a list of two lists, the first list contains keywords
  2294. to consider as TODO keywords, the second list contains keywords
  2295. to consider as DONE keywords.
  2296. When this is set, todo statistics is updated in the parent of the
  2297. current entry each time a todo state is changed."
  2298. :group 'org-todo
  2299. :type '(choice
  2300. (const :tag "Yes, only for TODO entries" t)
  2301. (const :tag "Yes, including all entries" all-headlines)
  2302. (repeat :tag "Yes, for TODOs in this list"
  2303. (string :tag "TODO keyword"))
  2304. (list :tag "Yes, for TODOs and DONEs in these lists"
  2305. (repeat (string :tag "TODO keyword"))
  2306. (repeat (string :tag "DONE keyword")))
  2307. (other :tag "No TODO statistics" nil)))
  2308. (defcustom org-hierarchical-todo-statistics t
  2309. "Non-nil means TODO statistics covers just direct children.
  2310. When nil, all entries in the subtree are considered.
  2311. This has only an effect if `org-provide-todo-statistics' is set.
  2312. To set this to nil for only a single subtree, use a COOKIE_DATA
  2313. property and include the word \"recursive\" into the value."
  2314. :group 'org-todo
  2315. :type 'boolean)
  2316. (defcustom org-after-todo-state-change-hook nil
  2317. "Hook which is run after the state of a TODO item was changed.
  2318. The new state (a string with a TODO keyword, or nil) is available in the
  2319. Lisp variable `org-state'."
  2320. :group 'org-todo
  2321. :type 'hook)
  2322. (defvar org-blocker-hook nil
  2323. "Hook for functions that are allowed to block a state change.
  2324. Functions in this hook should not modify the buffer.
  2325. Each function gets as its single argument a property list,
  2326. see `org-trigger-hook' for more information about this list.
  2327. If any of the functions in this hook returns nil, the state change
  2328. is blocked.")
  2329. (defvar org-trigger-hook nil
  2330. "Hook for functions that are triggered by a state change.
  2331. Each function gets as its single argument a property list with at
  2332. least the following elements:
  2333. (:type type-of-change :position pos-at-entry-start
  2334. :from old-state :to new-state)
  2335. Depending on the type, more properties may be present.
  2336. This mechanism is currently implemented for:
  2337. TODO state changes
  2338. ------------------
  2339. :type todo-state-change
  2340. :from previous state (keyword as a string), or nil, or a symbol
  2341. `todo' or `done', to indicate the general type of state.
  2342. :to new state, like in :from")
  2343. (defcustom org-enforce-todo-dependencies nil
  2344. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2345. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2346. be blocked if any prior sibling is not yet done.
  2347. Finally, if the parent is blocked because of ordered siblings of its own,
  2348. the child will also be blocked."
  2349. :set (lambda (var val)
  2350. (set var val)
  2351. (if val
  2352. (add-hook 'org-blocker-hook
  2353. 'org-block-todo-from-children-or-siblings-or-parent)
  2354. (remove-hook 'org-blocker-hook
  2355. 'org-block-todo-from-children-or-siblings-or-parent)))
  2356. :group 'org-todo
  2357. :type 'boolean)
  2358. (defcustom org-enforce-todo-checkbox-dependencies nil
  2359. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2360. When this is nil, checkboxes have no influence on switching TODO states.
  2361. When non-nil, you first need to check off all check boxes before the TODO
  2362. entry can be switched to DONE.
  2363. This variable needs to be set before org.el is loaded, and you need to
  2364. restart Emacs after a change to make the change effective. The only way
  2365. to change is while Emacs is running is through the customize interface."
  2366. :set (lambda (var val)
  2367. (set var val)
  2368. (if val
  2369. (add-hook 'org-blocker-hook
  2370. 'org-block-todo-from-checkboxes)
  2371. (remove-hook 'org-blocker-hook
  2372. 'org-block-todo-from-checkboxes)))
  2373. :group 'org-todo
  2374. :type 'boolean)
  2375. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2376. "Non-nil means inserting a TODO heading is treated as state change.
  2377. So when the command \\[org-insert-todo-heading] is used, state change
  2378. logging will apply if appropriate. When nil, the new TODO item will
  2379. be inserted directly, and no logging will take place."
  2380. :group 'org-todo
  2381. :type 'boolean)
  2382. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2383. "Non-nil means switching TODO states with S-cursor counts as state change.
  2384. This is the default behavior. However, setting this to nil allows a
  2385. convenient way to select a TODO state and bypass any logging associated
  2386. with that."
  2387. :group 'org-todo
  2388. :type 'boolean)
  2389. (defcustom org-todo-state-tags-triggers nil
  2390. "Tag changes that should be triggered by TODO state changes.
  2391. This is a list. Each entry is
  2392. (state-change (tag . flag) .......)
  2393. State-change can be a string with a state, and empty string to indicate the
  2394. state that has no TODO keyword, or it can be one of the symbols `todo'
  2395. or `done', meaning any not-done or done state, respectively."
  2396. :group 'org-todo
  2397. :group 'org-tags
  2398. :type '(repeat
  2399. (cons (choice :tag "When changing to"
  2400. (const :tag "Not-done state" todo)
  2401. (const :tag "Done state" done)
  2402. (string :tag "State"))
  2403. (repeat
  2404. (cons :tag "Tag action"
  2405. (string :tag "Tag")
  2406. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2407. (defcustom org-log-done nil
  2408. "Information to record when a task moves to the DONE state.
  2409. Possible values are:
  2410. nil Don't add anything, just change the keyword
  2411. time Add a time stamp to the task
  2412. note Prompt for a note and add it with template `org-log-note-headings'
  2413. This option can also be set with on a per-file-basis with
  2414. #+STARTUP: nologdone
  2415. #+STARTUP: logdone
  2416. #+STARTUP: lognotedone
  2417. You can have local logging settings for a subtree by setting the LOGGING
  2418. property to one or more of these keywords."
  2419. :group 'org-todo
  2420. :group 'org-progress
  2421. :type '(choice
  2422. (const :tag "No logging" nil)
  2423. (const :tag "Record CLOSED timestamp" time)
  2424. (const :tag "Record CLOSED timestamp with note." note)))
  2425. ;; Normalize old uses of org-log-done.
  2426. (cond
  2427. ((eq org-log-done t) (setq org-log-done 'time))
  2428. ((and (listp org-log-done) (memq 'done org-log-done))
  2429. (setq org-log-done 'note)))
  2430. (defcustom org-log-reschedule nil
  2431. "Information to record when the scheduling date of a tasks is modified.
  2432. Possible values are:
  2433. nil Don't add anything, just change the date
  2434. time Add a time stamp to the task
  2435. note Prompt for a note and add it with template `org-log-note-headings'
  2436. This option can also be set with on a per-file-basis with
  2437. #+STARTUP: nologreschedule
  2438. #+STARTUP: logreschedule
  2439. #+STARTUP: lognotereschedule"
  2440. :group 'org-todo
  2441. :group 'org-progress
  2442. :type '(choice
  2443. (const :tag "No logging" nil)
  2444. (const :tag "Record timestamp" time)
  2445. (const :tag "Record timestamp with note." note)))
  2446. (defcustom org-log-redeadline nil
  2447. "Information to record when the deadline date of a tasks is modified.
  2448. Possible values are:
  2449. nil Don't add anything, just change the date
  2450. time Add a time stamp to the task
  2451. note Prompt for a note and add it with template `org-log-note-headings'
  2452. This option can also be set with on a per-file-basis with
  2453. #+STARTUP: nologredeadline
  2454. #+STARTUP: logredeadline
  2455. #+STARTUP: lognoteredeadline
  2456. You can have local logging settings for a subtree by setting the LOGGING
  2457. property to one or more of these keywords."
  2458. :group 'org-todo
  2459. :group 'org-progress
  2460. :type '(choice
  2461. (const :tag "No logging" nil)
  2462. (const :tag "Record timestamp" time)
  2463. (const :tag "Record timestamp with note." note)))
  2464. (defcustom org-log-note-clock-out nil
  2465. "Non-nil means record a note when clocking out of an item.
  2466. This can also be configured on a per-file basis by adding one of
  2467. the following lines anywhere in the buffer:
  2468. #+STARTUP: lognoteclock-out
  2469. #+STARTUP: nolognoteclock-out"
  2470. :group 'org-todo
  2471. :group 'org-progress
  2472. :type 'boolean)
  2473. (defcustom org-log-done-with-time t
  2474. "Non-nil means the CLOSED time stamp will contain date and time.
  2475. When nil, only the date will be recorded."
  2476. :group 'org-progress
  2477. :type 'boolean)
  2478. (defcustom org-log-note-headings
  2479. '((done . "CLOSING NOTE %t")
  2480. (state . "State %-12s from %-12S %t")
  2481. (note . "Note taken on %t")
  2482. (reschedule . "Rescheduled from %S on %t")
  2483. (delschedule . "Not scheduled, was %S on %t")
  2484. (redeadline . "New deadline from %S on %t")
  2485. (deldeadline . "Removed deadline, was %S on %t")
  2486. (refile . "Refiled on %t")
  2487. (clock-out . ""))
  2488. "Headings for notes added to entries.
  2489. The value is an alist, with the car being a symbol indicating the
  2490. note context, and the cdr is the heading to be used. The heading
  2491. may also be the empty string. The following placeholders can be
  2492. used:
  2493. %t a time stamp.
  2494. %T an active time stamp instead the default inactive one
  2495. %d a short-format time stamp.
  2496. %D an active short-format time stamp.
  2497. %s the new TODO state or time stamp (inactive), in double quotes.
  2498. %S the old TODO state or time stamp (inactive), in double quotes.
  2499. %u the user name.
  2500. %U full user name.
  2501. In fact, it is not a good idea to change the `state' entry,
  2502. because Agenda Log mode depends on the format of these entries."
  2503. :group 'org-todo
  2504. :group 'org-progress
  2505. :type '(list :greedy t
  2506. (cons (const :tag "Heading when closing an item" done) string)
  2507. (cons (const :tag
  2508. "Heading when changing todo state (todo sequence only)"
  2509. state) string)
  2510. (cons (const :tag "Heading when just taking a note" note) string)
  2511. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2512. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2513. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2514. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2515. (cons (const :tag "Heading when refiling" refile) string)
  2516. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2517. (unless (assq 'note org-log-note-headings)
  2518. (push '(note . "%t") org-log-note-headings))
  2519. (defcustom org-log-into-drawer nil
  2520. "Non-nil means insert state change notes and time stamps into a drawer.
  2521. When nil, state changes notes will be inserted after the headline and
  2522. any scheduling and clock lines, but not inside a drawer.
  2523. The value of this variable should be the name of the drawer to use.
  2524. LOGBOOK is proposed as the default drawer for this purpose, you can
  2525. also set this to a string to define the drawer of your choice.
  2526. A value of t is also allowed, representing \"LOGBOOK\".
  2527. A value of t or nil can also be set with on a per-file-basis with
  2528. #+STARTUP: logdrawer
  2529. #+STARTUP: nologdrawer
  2530. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2531. will be ignored.
  2532. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2533. a subtree.
  2534. Do not check directly this variable in a Lisp program. Call
  2535. function `org-log-into-drawer' instead."
  2536. :group 'org-todo
  2537. :group 'org-progress
  2538. :type '(choice
  2539. (const :tag "Not into a drawer" nil)
  2540. (const :tag "LOGBOOK" t)
  2541. (string :tag "Other")))
  2542. (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2543. (defun org-log-into-drawer ()
  2544. "Name of the log drawer, as a string, or nil.
  2545. This is the value of `org-log-into-drawer'. However, if the
  2546. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2547. be used instead of the default value."
  2548. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2549. (cond ((equal p "nil") nil)
  2550. ((equal p "t") "LOGBOOK")
  2551. ((stringp p) p)
  2552. (p "LOGBOOK")
  2553. ((stringp org-log-into-drawer) org-log-into-drawer)
  2554. (org-log-into-drawer "LOGBOOK"))))
  2555. (defcustom org-log-state-notes-insert-after-drawers nil
  2556. "Non-nil means insert state change notes after any drawers in entry.
  2557. Only the drawers that *immediately* follow the headline and the
  2558. deadline/scheduled line are skipped.
  2559. When nil, insert notes right after the heading and perhaps the line
  2560. with deadline/scheduling if present.
  2561. This variable will have no effect if `org-log-into-drawer' is
  2562. set."
  2563. :group 'org-todo
  2564. :group 'org-progress
  2565. :type 'boolean)
  2566. (defcustom org-log-states-order-reversed t
  2567. "Non-nil means the latest state note will be directly after heading.
  2568. When nil, the state change notes will be ordered according to time.
  2569. This option can also be set with on a per-file-basis with
  2570. #+STARTUP: logstatesreversed
  2571. #+STARTUP: nologstatesreversed"
  2572. :group 'org-todo
  2573. :group 'org-progress
  2574. :type 'boolean)
  2575. (defcustom org-todo-repeat-to-state nil
  2576. "The TODO state to which a repeater should return the repeating task.
  2577. By default this is the first task in a TODO sequence, or the previous state
  2578. in a TODO_TYP set. But you can specify another task here.
  2579. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2580. :group 'org-todo
  2581. :version "24.1"
  2582. :type '(choice (const :tag "Head of sequence" nil)
  2583. (string :tag "Specific state")))
  2584. (defcustom org-log-repeat 'time
  2585. "Non-nil means record moving through the DONE state when triggering repeat.
  2586. An auto-repeating task is immediately switched back to TODO when
  2587. marked DONE. If you are not logging state changes (by adding \"@\"
  2588. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2589. record a closing note, there will be no record of the task moving
  2590. through DONE. This variable forces taking a note anyway.
  2591. nil Don't force a record
  2592. time Record a time stamp
  2593. note Prompt for a note and add it with template `org-log-note-headings'
  2594. This option can also be set with on a per-file-basis with
  2595. #+STARTUP: nologrepeat
  2596. #+STARTUP: logrepeat
  2597. #+STARTUP: lognoterepeat
  2598. You can have local logging settings for a subtree by setting the LOGGING
  2599. property to one or more of these keywords."
  2600. :group 'org-todo
  2601. :group 'org-progress
  2602. :type '(choice
  2603. (const :tag "Don't force a record" nil)
  2604. (const :tag "Force recording the DONE state" time)
  2605. (const :tag "Force recording a note with the DONE state" note)))
  2606. (defgroup org-priorities nil
  2607. "Priorities in Org-mode."
  2608. :tag "Org Priorities"
  2609. :group 'org-todo)
  2610. (defcustom org-enable-priority-commands t
  2611. "Non-nil means priority commands are active.
  2612. When nil, these commands will be disabled, so that you never accidentally
  2613. set a priority."
  2614. :group 'org-priorities
  2615. :type 'boolean)
  2616. (defcustom org-highest-priority ?A
  2617. "The highest priority of TODO items. A character like ?A, ?B etc.
  2618. Must have a smaller ASCII number than `org-lowest-priority'."
  2619. :group 'org-priorities
  2620. :type 'character)
  2621. (defcustom org-lowest-priority ?C
  2622. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2623. Must have a larger ASCII number than `org-highest-priority'."
  2624. :group 'org-priorities
  2625. :type 'character)
  2626. (defcustom org-default-priority ?B
  2627. "The default priority of TODO items.
  2628. This is the priority an item gets if no explicit priority is given.
  2629. When starting to cycle on an empty priority the first step in the cycle
  2630. depends on `org-priority-start-cycle-with-default'. The resulting first
  2631. step priority must not exceed the range from `org-highest-priority' to
  2632. `org-lowest-priority' which means that `org-default-priority' has to be
  2633. in this range exclusive or inclusive the range boundaries. Else the
  2634. first step refuses to set the default and the second will fall back
  2635. to (depending on the command used) the highest or lowest priority."
  2636. :group 'org-priorities
  2637. :type 'character)
  2638. (defcustom org-priority-start-cycle-with-default t
  2639. "Non-nil means start with default priority when starting to cycle.
  2640. When this is nil, the first step in the cycle will be (depending on the
  2641. command used) one higher or lower than the default priority.
  2642. See also `org-default-priority'."
  2643. :group 'org-priorities
  2644. :type 'boolean)
  2645. (defcustom org-get-priority-function nil
  2646. "Function to extract the priority from a string.
  2647. The string is normally the headline. If this is nil Org computes the
  2648. priority from the priority cookie like [#A] in the headline. It returns
  2649. an integer, increasing by 1000 for each priority level.
  2650. The user can set a different function here, which should take a string
  2651. as an argument and return the numeric priority."
  2652. :group 'org-priorities
  2653. :version "24.1"
  2654. :type '(choice
  2655. (const nil)
  2656. (function)))
  2657. (defgroup org-time nil
  2658. "Options concerning time stamps and deadlines in Org-mode."
  2659. :tag "Org Time"
  2660. :group 'org)
  2661. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2662. "Number of minutes to round time stamps to.
  2663. \\<org-mode-map>\
  2664. These are two values, the first applies when first creating a time stamp.
  2665. The second applies when changing it with the commands `S-up' and `S-down'.
  2666. When changing the time stamp, this means that it will change in steps
  2667. of N minutes, as given by the second value.
  2668. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2669. numbers should be factors of 60, so for example 5, 10, 15.
  2670. When this is larger than 1, you can still force an exact time stamp by using
  2671. a double prefix argument to a time stamp command like \
  2672. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2673. and by using a prefix arg to `S-up/down' to specify the exact number
  2674. of minutes to shift."
  2675. :group 'org-time
  2676. :get (lambda (var) ; Make sure both elements are there
  2677. (if (integerp (default-value var))
  2678. (list (default-value var) 5)
  2679. (default-value var)))
  2680. :type '(list
  2681. (integer :tag "when inserting times")
  2682. (integer :tag "when modifying times")))
  2683. ;; Normalize old customizations of this variable.
  2684. (when (integerp org-time-stamp-rounding-minutes)
  2685. (setq org-time-stamp-rounding-minutes
  2686. (list org-time-stamp-rounding-minutes
  2687. org-time-stamp-rounding-minutes)))
  2688. (defcustom org-display-custom-times nil
  2689. "Non-nil means overlay custom formats over all time stamps.
  2690. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2691. To turn this on on a per-file basis, insert anywhere in the file:
  2692. #+STARTUP: customtime"
  2693. :group 'org-time
  2694. :set 'set-default
  2695. :type 'sexp)
  2696. (make-variable-buffer-local 'org-display-custom-times)
  2697. (defcustom org-time-stamp-custom-formats
  2698. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2699. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2700. These are overlaid over the default ISO format if the variable
  2701. `org-display-custom-times' is set. Time like %H:%M should be at the
  2702. end of the second format. The custom formats are also honored by export
  2703. commands, if custom time display is turned on at the time of export."
  2704. :group 'org-time
  2705. :type 'sexp)
  2706. (defun org-time-stamp-format (&optional long inactive)
  2707. "Get the right format for a time string."
  2708. (let ((f (if long (cdr org-time-stamp-formats)
  2709. (car org-time-stamp-formats))))
  2710. (if inactive
  2711. (concat "[" (substring f 1 -1) "]")
  2712. f)))
  2713. (defcustom org-time-clocksum-format
  2714. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2715. "The format string used when creating CLOCKSUM lines.
  2716. This is also used when Org mode generates a time duration.
  2717. The value can be a single format string containing two
  2718. %-sequences, which will be filled with the number of hours and
  2719. minutes in that order.
  2720. Alternatively, the value can be a plist associating any of the
  2721. keys :years, :months, :weeks, :days, :hours or :minutes with
  2722. format strings. The time duration is formatted using only the
  2723. time components that are needed and concatenating the results.
  2724. If a time unit in absent, it falls back to the next smallest
  2725. unit.
  2726. The keys :require-years, :require-months, :require-days,
  2727. :require-weeks, :require-hours, :require-minutes are also
  2728. meaningful. A non-nil value for these keys indicates that the
  2729. corresponding time component should always be included, even if
  2730. its value is 0.
  2731. For example,
  2732. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2733. :require-minutes t)
  2734. means durations longer than a day will be expressed in days,
  2735. hours and minutes, and durations less than a day will always be
  2736. expressed in hours and minutes (even for durations less than an
  2737. hour).
  2738. The value
  2739. (:days \"%dd\" :minutes \"%dm\")
  2740. means durations longer than a day will be expressed in days and
  2741. minutes, and durations less than a day will be expressed entirely
  2742. in minutes (even for durations longer than an hour)."
  2743. :group 'org-time
  2744. :group 'org-clock
  2745. :version "24.4"
  2746. :package-version '(Org . "8.0")
  2747. :type '(choice (string :tag "Format string")
  2748. (set :tag "Plist"
  2749. (group :inline t (const :tag "Years" :years)
  2750. (string :tag "Format string"))
  2751. (group :inline t
  2752. (const :tag "Always show years" :require-years)
  2753. (const t))
  2754. (group :inline t (const :tag "Months" :months)
  2755. (string :tag "Format string"))
  2756. (group :inline t
  2757. (const :tag "Always show months" :require-months)
  2758. (const t))
  2759. (group :inline t (const :tag "Weeks" :weeks)
  2760. (string :tag "Format string"))
  2761. (group :inline t
  2762. (const :tag "Always show weeks" :require-weeks)
  2763. (const t))
  2764. (group :inline t (const :tag "Days" :days)
  2765. (string :tag "Format string"))
  2766. (group :inline t
  2767. (const :tag "Always show days" :require-days)
  2768. (const t))
  2769. (group :inline t (const :tag "Hours" :hours)
  2770. (string :tag "Format string"))
  2771. (group :inline t
  2772. (const :tag "Always show hours" :require-hours)
  2773. (const t))
  2774. (group :inline t (const :tag "Minutes" :minutes)
  2775. (string :tag "Format string"))
  2776. (group :inline t
  2777. (const :tag "Always show minutes" :require-minutes)
  2778. (const t)))))
  2779. (defcustom org-time-clocksum-use-fractional nil
  2780. "When non-nil, \\[org-clock-display] uses fractional times.
  2781. See `org-time-clocksum-format' for more on time clock formats."
  2782. :group 'org-time
  2783. :group 'org-clock
  2784. :version "24.3"
  2785. :type 'boolean)
  2786. (defcustom org-time-clocksum-use-effort-durations nil
  2787. "When non-nil, \\[org-clock-display] uses effort durations.
  2788. E.g. by default, one day is considered to be a 8 hours effort,
  2789. so a task that has been clocked for 16 hours will be displayed
  2790. as during 2 days in the clock display or in the clocktable.
  2791. See `org-effort-durations' on how to set effort durations
  2792. and `org-time-clocksum-format' for more on time clock formats."
  2793. :group 'org-time
  2794. :group 'org-clock
  2795. :version "24.4"
  2796. :package-version '(Org . "8.0")
  2797. :type 'boolean)
  2798. (defcustom org-time-clocksum-fractional-format "%.2f"
  2799. "The format string used when creating CLOCKSUM lines,
  2800. or when Org mode generates a time duration, if
  2801. `org-time-clocksum-use-fractional' is enabled.
  2802. The value can be a single format string containing one
  2803. %-sequence, which will be filled with the number of hours as
  2804. a float.
  2805. Alternatively, the value can be a plist associating any of the
  2806. keys :years, :months, :weeks, :days, :hours or :minutes with
  2807. a format string. The time duration is formatted using the
  2808. largest time unit which gives a non-zero integer part. If all
  2809. specified formats have zero integer part, the smallest time unit
  2810. is used."
  2811. :group 'org-time
  2812. :type '(choice (string :tag "Format string")
  2813. (set (group :inline t (const :tag "Years" :years)
  2814. (string :tag "Format string"))
  2815. (group :inline t (const :tag "Months" :months)
  2816. (string :tag "Format string"))
  2817. (group :inline t (const :tag "Weeks" :weeks)
  2818. (string :tag "Format string"))
  2819. (group :inline t (const :tag "Days" :days)
  2820. (string :tag "Format string"))
  2821. (group :inline t (const :tag "Hours" :hours)
  2822. (string :tag "Format string"))
  2823. (group :inline t (const :tag "Minutes" :minutes)
  2824. (string :tag "Format string")))))
  2825. (defcustom org-deadline-warning-days 14
  2826. "Number of days before expiration during which a deadline becomes active.
  2827. This variable governs the display in sparse trees and in the agenda.
  2828. When 0 or negative, it means use this number (the absolute value of it)
  2829. even if a deadline has a different individual lead time specified.
  2830. Custom commands can set this variable in the options section."
  2831. :group 'org-time
  2832. :group 'org-agenda-daily/weekly
  2833. :type 'integer)
  2834. (defcustom org-scheduled-delay-days 0
  2835. "Number of days before a scheduled item becomes active.
  2836. This variable governs the display in sparse trees and in the agenda.
  2837. The default value (i.e. 0) means: don't delay scheduled item.
  2838. When negative, it means use this number (the absolute value of it)
  2839. even if a scheduled item has a different individual delay time
  2840. specified.
  2841. Custom commands can set this variable in the options section."
  2842. :group 'org-time
  2843. :group 'org-agenda-daily/weekly
  2844. :version "24.4"
  2845. :package-version '(Org . "8.0")
  2846. :type 'integer)
  2847. (defcustom org-read-date-prefer-future t
  2848. "Non-nil means assume future for incomplete date input from user.
  2849. This affects the following situations:
  2850. 1. The user gives a month but not a year.
  2851. For example, if it is April and you enter \"feb 2\", this will be read
  2852. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2853. 2. The user gives a day, but no month.
  2854. For example, if today is the 15th, and you enter \"3\", Org-mode will
  2855. read this as the third of *next* month. However, if you enter \"17\",
  2856. it will be considered as *this* month.
  2857. If you set this variable to the symbol `time', then also the following
  2858. will work:
  2859. 3. If the user gives a time.
  2860. If the time is before now, it will be interpreted as tomorrow.
  2861. Currently none of this works for ISO week specifications.
  2862. When this option is nil, the current day, month and year will always be
  2863. used as defaults.
  2864. See also `org-agenda-jump-prefer-future'."
  2865. :group 'org-time
  2866. :type '(choice
  2867. (const :tag "Never" nil)
  2868. (const :tag "Check month and day" t)
  2869. (const :tag "Check month, day, and time" time)))
  2870. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2871. "Should the agenda jump command prefer the future for incomplete dates?
  2872. The default is to do the same as configured in `org-read-date-prefer-future'.
  2873. But you can also set a deviating value here.
  2874. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2875. :group 'org-agenda
  2876. :group 'org-time
  2877. :version "24.1"
  2878. :type '(choice
  2879. (const :tag "Use org-read-date-prefer-future"
  2880. org-read-date-prefer-future)
  2881. (const :tag "Never" nil)
  2882. (const :tag "Always" t)))
  2883. (defcustom org-read-date-force-compatible-dates t
  2884. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2885. Depending on the system Emacs is running on, certain dates cannot
  2886. be represented with the type used internally to represent time.
  2887. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2888. correctly. Some systems allow for earlier dates, some for later,
  2889. some for both. One way to find out it to insert any date into an
  2890. Org buffer, putting the cursor on the year and hitting S-up and
  2891. S-down to test the range.
  2892. When this variable is set to t, the date/time prompt will not let
  2893. you specify dates outside the 1970-2037 range, so it is certain that
  2894. these dates will work in whatever version of Emacs you are
  2895. running, and also that you can move a file from one Emacs implementation
  2896. to another. WHenever Org is forcing the year for you, it will display
  2897. a message and beep.
  2898. When this variable is nil, Org will check if the date is
  2899. representable in the specific Emacs implementation you are using.
  2900. If not, it will force a year, usually the current year, and beep
  2901. to remind you. Currently this setting is not recommended because
  2902. the likelihood that you will open your Org files in an Emacs that
  2903. has limited date range is not negligible.
  2904. A workaround for this problem is to use diary sexp dates for time
  2905. stamps outside of this range."
  2906. :group 'org-time
  2907. :version "24.1"
  2908. :type 'boolean)
  2909. (defcustom org-read-date-display-live t
  2910. "Non-nil means display current interpretation of date prompt live.
  2911. This display will be in an overlay, in the minibuffer."
  2912. :group 'org-time
  2913. :type 'boolean)
  2914. (defcustom org-read-date-popup-calendar t
  2915. "Non-nil means pop up a calendar when prompting for a date.
  2916. In the calendar, the date can be selected with mouse-1. However, the
  2917. minibuffer will also be active, and you can simply enter the date as well.
  2918. When nil, only the minibuffer will be available."
  2919. :group 'org-time
  2920. :type 'boolean)
  2921. (org-defvaralias 'org-popup-calendar-for-date-prompt
  2922. 'org-read-date-popup-calendar)
  2923. (make-obsolete-variable
  2924. 'org-read-date-minibuffer-setup-hook
  2925. "Set `org-read-date-minibuffer-local-map' instead." "24.4")
  2926. (defcustom org-read-date-minibuffer-setup-hook nil
  2927. "Hook to be used to set up keys for the date/time interface.
  2928. Add key definitions to `minibuffer-local-map', which will be a
  2929. temporary copy.
  2930. WARNING: This option is obsolete, you should use
  2931. `org-read-date-minibuffer-local-map' to set up keys."
  2932. :group 'org-time
  2933. :type 'hook)
  2934. (defcustom org-extend-today-until 0
  2935. "The hour when your day really ends. Must be an integer.
  2936. This has influence for the following applications:
  2937. - When switching the agenda to \"today\". It it is still earlier than
  2938. the time given here, the day recognized as TODAY is actually yesterday.
  2939. - When a date is read from the user and it is still before the time given
  2940. here, the current date and time will be assumed to be yesterday, 23:59.
  2941. Also, timestamps inserted in capture templates follow this rule.
  2942. IMPORTANT: This is a feature whose implementation is and likely will
  2943. remain incomplete. Really, it is only here because past midnight seems to
  2944. be the favorite working time of John Wiegley :-)"
  2945. :group 'org-time
  2946. :type 'integer)
  2947. (defcustom org-use-effective-time nil
  2948. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2949. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2950. \"effective time\" of any timestamps between midnight and 8am will be
  2951. 23:59 of the previous day."
  2952. :group 'org-time
  2953. :version "24.1"
  2954. :type 'boolean)
  2955. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2956. "When non-nil, use the last clock out time for `org-todo'.
  2957. Note that this option has precedence over the combined use of
  2958. `org-use-effective-time' and `org-extend-today-until'."
  2959. :group 'org-time
  2960. :version "24.4"
  2961. :package-version '(Org . "8.0")
  2962. :type 'boolean)
  2963. (defcustom org-edit-timestamp-down-means-later nil
  2964. "Non-nil means S-down will increase the time in a time stamp.
  2965. When nil, S-up will increase."
  2966. :group 'org-time
  2967. :type 'boolean)
  2968. (defcustom org-calendar-follow-timestamp-change t
  2969. "Non-nil means make the calendar window follow timestamp changes.
  2970. When a timestamp is modified and the calendar window is visible, it will be
  2971. moved to the new date."
  2972. :group 'org-time
  2973. :type 'boolean)
  2974. (defgroup org-tags nil
  2975. "Options concerning tags in Org-mode."
  2976. :tag "Org Tags"
  2977. :group 'org)
  2978. (defcustom org-tag-alist nil
  2979. "List of tags allowed in Org-mode files.
  2980. When this list is nil, Org-mode will base TAG input on what is already in the
  2981. buffer.
  2982. The value of this variable is an alist, the car of each entry must be a
  2983. keyword as a string, the cdr may be a character that is used to select
  2984. that tag through the fast-tag-selection interface.
  2985. See the manual for details."
  2986. :group 'org-tags
  2987. :type '(repeat
  2988. (choice
  2989. (cons (string :tag "Tag name")
  2990. (character :tag "Access char"))
  2991. (list :tag "Start radio group"
  2992. (const :startgroup)
  2993. (option (string :tag "Group description")))
  2994. (list :tag "Start tag group, non distinct"
  2995. (const :startgrouptag)
  2996. (option (string :tag "Group description")))
  2997. (list :tag "Group tags delimiter"
  2998. (const :grouptags))
  2999. (list :tag "End radio group"
  3000. (const :endgroup)
  3001. (option (string :tag "Group description")))
  3002. (list :tag "End tag group, non distinct"
  3003. (const :endgrouptag)
  3004. (option (string :tag "Group description")))
  3005. (const :tag "New line" (:newline)))))
  3006. (defcustom org-tag-persistent-alist nil
  3007. "List of tags that will always appear in all Org-mode files.
  3008. This is in addition to any in buffer settings or customizations
  3009. of `org-tag-alist'.
  3010. When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
  3011. The value of this variable is an alist, the car of each entry must be a
  3012. keyword as a string, the cdr may be a character that is used to select
  3013. that tag through the fast-tag-selection interface.
  3014. See the manual for details.
  3015. To disable these tags on a per-file basis, insert anywhere in the file:
  3016. #+STARTUP: noptag"
  3017. :group 'org-tags
  3018. :type '(repeat
  3019. (choice
  3020. (cons (string :tag "Tag name")
  3021. (character :tag "Access char"))
  3022. (const :tag "Start radio group" (:startgroup))
  3023. (const :tag "Group tags delimiter" (:grouptags))
  3024. (const :tag "End radio group" (:endgroup))
  3025. (const :tag "New line" (:newline)))))
  3026. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3027. "If non-nil, always offer completion for all tags of all agenda files.
  3028. Instead of customizing this variable directly, you might want to
  3029. set it locally for capture buffers, because there no list of
  3030. tags in that file can be created dynamically (there are none).
  3031. (add-hook \\='org-capture-mode-hook
  3032. (lambda ()
  3033. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3034. :group 'org-tags
  3035. :version "24.1"
  3036. :type 'boolean)
  3037. (defvar org-file-tags nil
  3038. "List of tags that can be inherited by all entries in the file.
  3039. The tags will be inherited if the variable `org-use-tag-inheritance'
  3040. says they should be.
  3041. This variable is populated from #+FILETAGS lines.")
  3042. (defcustom org-use-fast-tag-selection 'auto
  3043. "Non-nil means use fast tag selection scheme.
  3044. This is a special interface to select and deselect tags with single keys.
  3045. When nil, fast selection is never used.
  3046. When the symbol `auto', fast selection is used if and only if selection
  3047. characters for tags have been configured, either through the variable
  3048. `org-tag-alist' or through a #+TAGS line in the buffer.
  3049. When t, fast selection is always used and selection keys are assigned
  3050. automatically if necessary."
  3051. :group 'org-tags
  3052. :type '(choice
  3053. (const :tag "Always" t)
  3054. (const :tag "Never" nil)
  3055. (const :tag "When selection characters are configured" auto)))
  3056. (defcustom org-fast-tag-selection-single-key nil
  3057. "Non-nil means fast tag selection exits after first change.
  3058. When nil, you have to press RET to exit it.
  3059. During fast tag selection, you can toggle this flag with `C-c'.
  3060. This variable can also have the value `expert'. In this case, the window
  3061. displaying the tags menu is not even shown, until you press C-c again."
  3062. :group 'org-tags
  3063. :type '(choice
  3064. (const :tag "No" nil)
  3065. (const :tag "Yes" t)
  3066. (const :tag "Expert" expert)))
  3067. (defvar org-fast-tag-selection-include-todo nil
  3068. "Non-nil means fast tags selection interface will also offer TODO states.
  3069. This is an undocumented feature, you should not rely on it.")
  3070. (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
  3071. "The column to which tags should be indented in a headline.
  3072. If this number is positive, it specifies the column. If it is negative,
  3073. it means that the tags should be flushright to that column. For example,
  3074. -80 works well for a normal 80 character screen.
  3075. When 0, place tags directly after headline text, with only one space in
  3076. between."
  3077. :group 'org-tags
  3078. :type 'integer)
  3079. (defcustom org-auto-align-tags t
  3080. "Non-nil keeps tags aligned when modifying headlines.
  3081. Some operations (i.e. demoting) change the length of a headline and
  3082. therefore shift the tags around. With this option turned on, after
  3083. each such operation the tags are again aligned to `org-tags-column'."
  3084. :group 'org-tags
  3085. :type 'boolean)
  3086. (defcustom org-use-tag-inheritance t
  3087. "Non-nil means tags in levels apply also for sublevels.
  3088. When nil, only the tags directly given in a specific line apply there.
  3089. This may also be a list of tags that should be inherited, or a regexp that
  3090. matches tags that should be inherited. Additional control is possible
  3091. with the variable `org-tags-exclude-from-inheritance' which gives an
  3092. explicit list of tags to be excluded from inheritance, even if the value of
  3093. `org-use-tag-inheritance' would select it for inheritance.
  3094. If this option is t, a match early-on in a tree can lead to a large
  3095. number of matches in the subtree when constructing the agenda or creating
  3096. a sparse tree. If you only want to see the first match in a tree during
  3097. a search, check out the variable `org-tags-match-list-sublevels'."
  3098. :group 'org-tags
  3099. :type '(choice
  3100. (const :tag "Not" nil)
  3101. (const :tag "Always" t)
  3102. (repeat :tag "Specific tags" (string :tag "Tag"))
  3103. (regexp :tag "Tags matched by regexp")))
  3104. (defcustom org-tags-exclude-from-inheritance nil
  3105. "List of tags that should never be inherited.
  3106. This is a way to exclude a few tags from inheritance. For way to do
  3107. the opposite, to actively allow inheritance for selected tags,
  3108. see the variable `org-use-tag-inheritance'."
  3109. :group 'org-tags
  3110. :type '(repeat (string :tag "Tag")))
  3111. (defun org-tag-inherit-p (tag)
  3112. "Check if TAG is one that should be inherited."
  3113. (cond
  3114. ((member tag org-tags-exclude-from-inheritance) nil)
  3115. ((eq org-use-tag-inheritance t) t)
  3116. ((not org-use-tag-inheritance) nil)
  3117. ((stringp org-use-tag-inheritance)
  3118. (string-match org-use-tag-inheritance tag))
  3119. ((listp org-use-tag-inheritance)
  3120. (member tag org-use-tag-inheritance))
  3121. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3122. (defcustom org-tags-match-list-sublevels t
  3123. "Non-nil means list also sublevels of headlines matching a search.
  3124. This variable applies to tags/property searches, and also to stuck
  3125. projects because this search is based on a tags match as well.
  3126. When set to the symbol `indented', sublevels are indented with
  3127. leading dots.
  3128. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3129. the sublevels of a headline matching a tag search often also match
  3130. the same search. Listing all of them can create very long lists.
  3131. Setting this variable to nil causes subtrees of a match to be skipped.
  3132. This variable is semi-obsolete and probably should always be true. It
  3133. is better to limit inheritance to certain tags using the variables
  3134. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3135. :group 'org-tags
  3136. :type '(choice
  3137. (const :tag "No, don't list them" nil)
  3138. (const :tag "Yes, do list them" t)
  3139. (const :tag "List them, indented with leading dots" indented)))
  3140. (defcustom org-tags-sort-function nil
  3141. "When set, tags are sorted using this function as a comparator."
  3142. :group 'org-tags
  3143. :type '(choice
  3144. (const :tag "No sorting" nil)
  3145. (const :tag "Alphabetical" string<)
  3146. (const :tag "Reverse alphabetical" string>)
  3147. (function :tag "Custom function" nil)))
  3148. (defvar org-tags-history nil
  3149. "History of minibuffer reads for tags.")
  3150. (defvar org-last-tags-completion-table nil
  3151. "The last used completion table for tags.")
  3152. (defvar org-after-tags-change-hook nil
  3153. "Hook that is run after the tags in a line have changed.")
  3154. (defgroup org-properties nil
  3155. "Options concerning properties in Org-mode."
  3156. :tag "Org Properties"
  3157. :group 'org)
  3158. (defcustom org-property-format "%-10s %s"
  3159. "How property key/value pairs should be formatted by `indent-line'.
  3160. When `indent-line' hits a property definition, it will format the line
  3161. according to this format, mainly to make sure that the values are
  3162. lined-up with respect to each other."
  3163. :group 'org-properties
  3164. :type 'string)
  3165. (defcustom org-properties-postprocess-alist nil
  3166. "Alist of properties and functions to adjust inserted values.
  3167. Elements of this alist must be of the form
  3168. ([string] [function])
  3169. where [string] must be a property name and [function] must be a
  3170. lambda expression: this lambda expression must take one argument,
  3171. the value to adjust, and return the new value as a string.
  3172. For example, this element will allow the property \"Remaining\"
  3173. to be updated wrt the relation between the \"Effort\" property
  3174. and the clock summary:
  3175. ((\"Remaining\" (lambda(value)
  3176. (let ((clocksum (org-clock-sum-current-item))
  3177. (effort (org-duration-string-to-minutes
  3178. (org-entry-get (point) \"Effort\"))))
  3179. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3180. :group 'org-properties
  3181. :version "24.1"
  3182. :type '(alist :key-type (string :tag "Property")
  3183. :value-type (function :tag "Function")))
  3184. (defcustom org-use-property-inheritance nil
  3185. "Non-nil means properties apply also for sublevels.
  3186. This setting is chiefly used during property searches. Turning it on can
  3187. cause significant overhead when doing a search, which is why it is not
  3188. on by default.
  3189. When nil, only the properties directly given in the current entry count.
  3190. When t, every property is inherited. The value may also be a list of
  3191. properties that should have inheritance, or a regular expression matching
  3192. properties that should be inherited.
  3193. However, note that some special properties use inheritance under special
  3194. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3195. and the properties ending in \"_ALL\" when they are used as descriptor
  3196. for valid values of a property.
  3197. Note for programmers:
  3198. When querying an entry with `org-entry-get', you can control if inheritance
  3199. should be used. By default, `org-entry-get' looks only at the local
  3200. properties. You can request inheritance by setting the inherit argument
  3201. to t (to force inheritance) or to `selective' (to respect the setting
  3202. in this variable)."
  3203. :group 'org-properties
  3204. :type '(choice
  3205. (const :tag "Not" nil)
  3206. (const :tag "Always" t)
  3207. (repeat :tag "Specific properties" (string :tag "Property"))
  3208. (regexp :tag "Properties matched by regexp")))
  3209. (defun org-property-inherit-p (property)
  3210. "Check if PROPERTY is one that should be inherited."
  3211. (cond
  3212. ((eq org-use-property-inheritance t) t)
  3213. ((not org-use-property-inheritance) nil)
  3214. ((stringp org-use-property-inheritance)
  3215. (string-match org-use-property-inheritance property))
  3216. ((listp org-use-property-inheritance)
  3217. (member property org-use-property-inheritance))
  3218. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3219. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3220. "The default column format, if no other format has been defined.
  3221. This variable can be set on the per-file basis by inserting a line
  3222. #+COLUMNS: %25ITEM ....."
  3223. :group 'org-properties
  3224. :type 'string)
  3225. (defcustom org-columns-ellipses ".."
  3226. "The ellipses to be used when a field in column view is truncated.
  3227. When this is the empty string, as many characters as possible are shown,
  3228. but then there will be no visual indication that the field has been truncated.
  3229. When this is a string of length N, the last N characters of a truncated
  3230. field are replaced by this string. If the column is narrower than the
  3231. ellipses string, only part of the ellipses string will be shown."
  3232. :group 'org-properties
  3233. :type 'string)
  3234. (defcustom org-columns-modify-value-for-display-function nil
  3235. "Function that modifies values for display in column view.
  3236. For example, it can be used to cut out a certain part from a time stamp.
  3237. The function must take 2 arguments:
  3238. column-title The title of the column (*not* the property name)
  3239. value The value that should be modified.
  3240. The function should return the value that should be displayed,
  3241. or nil if the normal value should be used."
  3242. :group 'org-properties
  3243. :type '(choice (const nil) (function)))
  3244. (defconst org-global-properties-fixed
  3245. '(("VISIBILITY_ALL" . "folded children content all")
  3246. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3247. "List of property/value pairs that can be inherited by any entry.
  3248. These are fixed values, for the preset properties. The user variable
  3249. that can be used to add to this list is `org-global-properties'.
  3250. The entries in this list are cons cells where the car is a property
  3251. name and cdr is a string with the value. If the value represents
  3252. multiple items like an \"_ALL\" property, separate the items by
  3253. spaces.")
  3254. (defcustom org-global-properties nil
  3255. "List of property/value pairs that can be inherited by any entry.
  3256. This list will be combined with the constant `org-global-properties-fixed'.
  3257. The entries in this list are cons cells where the car is a property
  3258. name and cdr is a string with the value.
  3259. You can set buffer-local values for the same purpose in the variable
  3260. `org-file-properties' this by adding lines like
  3261. #+PROPERTY: NAME VALUE"
  3262. :group 'org-properties
  3263. :type '(repeat
  3264. (cons (string :tag "Property")
  3265. (string :tag "Value"))))
  3266. (defvar-local org-file-properties nil
  3267. "List of property/value pairs that can be inherited by any entry.
  3268. Valid for the current buffer.
  3269. This variable is populated from #+PROPERTY lines.")
  3270. (defgroup org-agenda nil
  3271. "Options concerning agenda views in Org-mode."
  3272. :tag "Org Agenda"
  3273. :group 'org)
  3274. (defvar-local org-category nil
  3275. "Variable used by org files to set a category for agenda display.
  3276. Such files should use a file variable to set it, for example
  3277. # -*- mode: org; org-category: \"ELisp\"
  3278. or contain a special line
  3279. #+CATEGORY: ELisp
  3280. If the file does not specify a category, then file's base name
  3281. is used instead.")
  3282. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3283. (defcustom org-agenda-files nil
  3284. "The files to be used for agenda display.
  3285. Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
  3286. \\[org-remove-file]. You can also use customize to edit the list.
  3287. If an entry is a directory, all files in that directory that are matched by
  3288. `org-agenda-file-regexp' will be part of the file list.
  3289. If the value of the variable is not a list but a single file name, then
  3290. the list of agenda files is actually stored and maintained in that file, one
  3291. agenda file per line. In this file paths can be given relative to
  3292. `org-directory'. Tilde expansion and environment variable substitution
  3293. are also made."
  3294. :group 'org-agenda
  3295. :type '(choice
  3296. (repeat :tag "List of files and directories" file)
  3297. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3298. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3299. "Regular expression to match files for `org-agenda-files'.
  3300. If any element in the list in that variable contains a directory instead
  3301. of a normal file, all files in that directory that are matched by this
  3302. regular expression will be included."
  3303. :group 'org-agenda
  3304. :type 'regexp)
  3305. (defcustom org-agenda-text-search-extra-files nil
  3306. "List of extra files to be searched by text search commands.
  3307. These files will be searched in addition to the agenda files by the
  3308. commands `org-search-view' (`\\[org-agenda] s') \
  3309. and `org-occur-in-agenda-files'.
  3310. Note that these files will only be searched for text search commands,
  3311. not for the other agenda views like todo lists, tag searches or the weekly
  3312. agenda. This variable is intended to list notes and possibly archive files
  3313. that should also be searched by these two commands.
  3314. In fact, if the first element in the list is the symbol `agenda-archives',
  3315. then all archive files of all agenda files will be added to the search
  3316. scope."
  3317. :group 'org-agenda
  3318. :type '(set :greedy t
  3319. (const :tag "Agenda Archives" agenda-archives)
  3320. (repeat :inline t (file))))
  3321. (org-defvaralias 'org-agenda-multi-occur-extra-files
  3322. 'org-agenda-text-search-extra-files)
  3323. (defcustom org-agenda-skip-unavailable-files nil
  3324. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3325. A nil value means to remove them, after a query, from the list."
  3326. :group 'org-agenda
  3327. :type 'boolean)
  3328. (defcustom org-calendar-to-agenda-key [?c]
  3329. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3330. The command `org-calendar-goto-agenda' will be bound to this key. The
  3331. default is the character `c' because then `c' can be used to switch back and
  3332. forth between agenda and calendar."
  3333. :group 'org-agenda
  3334. :type 'sexp)
  3335. (defcustom org-calendar-insert-diary-entry-key [?i]
  3336. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3337. This option is irrelevant until `org-agenda-diary-file' has been configured
  3338. to point to an Org-mode file. When that is the case, the command
  3339. `org-agenda-diary-entry' will be bound to the key given here, by default
  3340. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3341. if you want to continue doing this, you need to change this to a different
  3342. key."
  3343. :group 'org-agenda
  3344. :type 'sexp)
  3345. (defcustom org-agenda-diary-file 'diary-file
  3346. "File to which to add new entries with the `i' key in agenda and calendar.
  3347. When this is the symbol `diary-file', the functionality in the Emacs
  3348. calendar will be used to add entries to the `diary-file'. But when this
  3349. points to a file, `org-agenda-diary-entry' will be used instead."
  3350. :group 'org-agenda
  3351. :type '(choice
  3352. (const :tag "The standard Emacs diary file" diary-file)
  3353. (file :tag "Special Org file diary entries")))
  3354. (eval-after-load "calendar"
  3355. '(progn
  3356. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3357. 'org-calendar-goto-agenda)
  3358. (add-hook 'calendar-mode-hook
  3359. (lambda ()
  3360. (unless (eq org-agenda-diary-file 'diary-file)
  3361. (define-key calendar-mode-map
  3362. org-calendar-insert-diary-entry-key
  3363. 'org-agenda-diary-entry))))))
  3364. (defgroup org-latex nil
  3365. "Options for embedding LaTeX code into Org-mode."
  3366. :tag "Org LaTeX"
  3367. :group 'org)
  3368. (defcustom org-format-latex-options
  3369. '(:foreground default :background default :scale 1.0
  3370. :html-foreground "Black" :html-background "Transparent"
  3371. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3372. "Options for creating images from LaTeX fragments.
  3373. This is a property list with the following properties:
  3374. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3375. `default' means use the foreground of the default face.
  3376. `auto' means use the foreground from the text face.
  3377. :background the background color, or \"Transparent\".
  3378. `default' means use the background of the default face.
  3379. `auto' means use the background from the text face.
  3380. :scale a scaling factor for the size of the images, to get more pixels
  3381. :html-foreground, :html-background, :html-scale
  3382. the same numbers for HTML export.
  3383. :matchers a list indicating which matchers should be used to
  3384. find LaTeX fragments. Valid members of this list are:
  3385. \"begin\" find environments
  3386. \"$1\" find single characters surrounded by $.$
  3387. \"$\" find math expressions surrounded by $...$
  3388. \"$$\" find math expressions surrounded by $$....$$
  3389. \"\\(\" find math expressions surrounded by \\(...\\)
  3390. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3391. :group 'org-latex
  3392. :type 'plist)
  3393. (defcustom org-format-latex-signal-error t
  3394. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3395. When nil, just push out a message."
  3396. :group 'org-latex
  3397. :version "24.1"
  3398. :type 'boolean)
  3399. (defcustom org-latex-to-mathml-jar-file nil
  3400. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3401. Use this to specify additional executable file say a jar file.
  3402. When using MathToWeb as the converter, specify the full-path to
  3403. your mathtoweb.jar file."
  3404. :group 'org-latex
  3405. :version "24.1"
  3406. :type '(choice
  3407. (const :tag "None" nil)
  3408. (file :tag "JAR file" :must-match t)))
  3409. (defcustom org-latex-to-mathml-convert-command nil
  3410. "Command to convert LaTeX fragments to MathML.
  3411. Replace format-specifiers in the command as noted below and use
  3412. `shell-command' to convert LaTeX to MathML.
  3413. %j: Executable file in fully expanded form as specified by
  3414. `org-latex-to-mathml-jar-file'.
  3415. %I: Input LaTeX file in fully expanded form.
  3416. %i: The latex fragment to be converted.
  3417. %o: Output MathML file.
  3418. This command is used by `org-create-math-formula'.
  3419. When using MathToWeb as the converter, set this option to
  3420. \"java -jar %j -unicode -force -df %o %I\".
  3421. When using LaTeXML set this option to
  3422. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3423. :group 'org-latex
  3424. :version "24.1"
  3425. :type '(choice
  3426. (const :tag "None" nil)
  3427. (string :tag "\nShell command")))
  3428. (defcustom org-latex-create-formula-image-program 'dvipng
  3429. "Program to convert LaTeX fragments with.
  3430. dvipng Process the LaTeX fragments to dvi file, then convert
  3431. dvi files to png files using dvipng.
  3432. This will also include processing of non-math environments.
  3433. imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
  3434. to convert pdf files to png files"
  3435. :group 'org-latex
  3436. :version "24.1"
  3437. :type '(choice
  3438. (const :tag "dvipng" dvipng)
  3439. (const :tag "imagemagick" imagemagick)))
  3440. (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
  3441. "Path to store latex preview images.
  3442. A relative path here creates many directories relative to the
  3443. processed org files paths. An absolute path puts all preview
  3444. images at the same place."
  3445. :group 'org-latex
  3446. :version "24.3"
  3447. :type 'string)
  3448. (defun org-format-latex-mathml-available-p ()
  3449. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3450. (save-match-data
  3451. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3452. org-latex-to-mathml-convert-command)
  3453. (let ((executable (car (split-string
  3454. org-latex-to-mathml-convert-command))))
  3455. (when (executable-find executable)
  3456. (if (string-match
  3457. "%j" org-latex-to-mathml-convert-command)
  3458. (file-readable-p org-latex-to-mathml-jar-file)
  3459. t))))))
  3460. (defcustom org-format-latex-header "\\documentclass{article}
  3461. \\usepackage[usenames]{color}
  3462. \[PACKAGES]
  3463. \[DEFAULT-PACKAGES]
  3464. \\pagestyle{empty} % do not remove
  3465. % The settings below are copied from fullpage.sty
  3466. \\setlength{\\textwidth}{\\paperwidth}
  3467. \\addtolength{\\textwidth}{-3cm}
  3468. \\setlength{\\oddsidemargin}{1.5cm}
  3469. \\addtolength{\\oddsidemargin}{-2.54cm}
  3470. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3471. \\setlength{\\textheight}{\\paperheight}
  3472. \\addtolength{\\textheight}{-\\headheight}
  3473. \\addtolength{\\textheight}{-\\headsep}
  3474. \\addtolength{\\textheight}{-\\footskip}
  3475. \\addtolength{\\textheight}{-3cm}
  3476. \\setlength{\\topmargin}{1.5cm}
  3477. \\addtolength{\\topmargin}{-2.54cm}"
  3478. "The document header used for processing LaTeX fragments.
  3479. It is imperative that this header make sure that no page number
  3480. appears on the page. The package defined in the variables
  3481. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3482. will either replace the placeholder \"[PACKAGES]\" in this
  3483. header, or they will be appended."
  3484. :group 'org-latex
  3485. :type 'string)
  3486. (defun org-set-packages-alist (var val)
  3487. "Set the packages alist and make sure it has 3 elements per entry."
  3488. (set var (mapcar (lambda (x)
  3489. (if (and (consp x) (= (length x) 2))
  3490. (list (car x) (nth 1 x) t)
  3491. x))
  3492. val)))
  3493. (defun org-get-packages-alist (var)
  3494. "Get the packages alist and make sure it has 3 elements per entry."
  3495. (mapcar (lambda (x)
  3496. (if (and (consp x) (= (length x) 2))
  3497. (list (car x) (nth 1 x) t)
  3498. x))
  3499. (default-value var)))
  3500. (defcustom org-latex-default-packages-alist
  3501. '(("AUTO" "inputenc" t ("pdflatex"))
  3502. ("T1" "fontenc" t ("pdflatex"))
  3503. ("" "graphicx" t)
  3504. ("" "grffile" t)
  3505. ("" "longtable" nil)
  3506. ("" "wrapfig" nil)
  3507. ("" "rotating" nil)
  3508. ("normalem" "ulem" t)
  3509. ("" "amsmath" t)
  3510. ("" "textcomp" t)
  3511. ("" "amssymb" t)
  3512. ("" "capt-of" nil)
  3513. ("" "hyperref" nil))
  3514. "Alist of default packages to be inserted in the header.
  3515. Change this only if one of the packages here causes an
  3516. incompatibility with another package you are using.
  3517. The packages in this list are needed by one part or another of
  3518. Org mode to function properly:
  3519. - inputenc, fontenc: for basic font and character selection
  3520. - graphicx: for including images
  3521. - grffile: allow periods and spaces in graphics file names
  3522. - longtable: For multipage tables
  3523. - wrapfig: for figure placement
  3524. - rotating: for sideways figures and tables
  3525. - ulem: for underline and strike-through
  3526. - amsmath: for subscript and superscript and math environments
  3527. - textcomp, amssymb: for various symbols used
  3528. for interpreting the entities in `org-entities'. You can skip
  3529. some of these packages if you don't use any of their symbols.
  3530. - capt-of: for captions outside of floats
  3531. - hyperref: for cross references
  3532. Therefore you should not modify this variable unless you know
  3533. what you are doing. The one reason to change it anyway is that
  3534. you might be loading some other package that conflicts with one
  3535. of the default packages. Each element is either a cell or
  3536. a string.
  3537. A cell is of the format
  3538. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3539. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3540. when compiling LaTeX snippets into images for inclusion into
  3541. non-LaTeX output. COMPILERS is a list of compilers that should
  3542. include the package, see `org-latex-compiler'. If the document
  3543. compiler is not in the list, and the list is non-nil, the package
  3544. will not be inserted in the final document.
  3545. A string will be inserted as-is in the header of the document."
  3546. :group 'org-latex
  3547. :group 'org-export-latex
  3548. :set 'org-set-packages-alist
  3549. :get 'org-get-packages-alist
  3550. :version "25.1"
  3551. :package-version '(Org . "8.3")
  3552. :type '(repeat
  3553. (choice
  3554. (list :tag "options/package pair"
  3555. (string :tag "options")
  3556. (string :tag "package")
  3557. (boolean :tag "Snippet"))
  3558. (string :tag "A line of LaTeX"))))
  3559. (defcustom org-latex-packages-alist nil
  3560. "Alist of packages to be inserted in every LaTeX header.
  3561. These will be inserted after `org-latex-default-packages-alist'.
  3562. Each element is either a cell or a string.
  3563. A cell is of the format:
  3564. (\"options\" \"package\" SNIPPET-FLAG)
  3565. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3566. needed when turning LaTeX snippets into images for inclusion into
  3567. non-LaTeX output.
  3568. A string will be inserted as-is in the header of the document.
  3569. Make sure that you only list packages here which:
  3570. - you want in every file;
  3571. - do not conflict with the setup in `org-format-latex-header';
  3572. - do not conflict with the default packages in
  3573. `org-latex-default-packages-alist'."
  3574. :group 'org-latex
  3575. :group 'org-export-latex
  3576. :set 'org-set-packages-alist
  3577. :get 'org-get-packages-alist
  3578. :type '(repeat
  3579. (choice
  3580. (list :tag "options/package pair"
  3581. (string :tag "options")
  3582. (string :tag "package")
  3583. (boolean :tag "Snippet"))
  3584. (string :tag "A line of LaTeX"))))
  3585. (defgroup org-appearance nil
  3586. "Settings for Org-mode appearance."
  3587. :tag "Org Appearance"
  3588. :group 'org)
  3589. (defcustom org-level-color-stars-only nil
  3590. "Non-nil means fontify only the stars in each headline.
  3591. When nil, the entire headline is fontified.
  3592. Changing it requires restart of `font-lock-mode' to become effective
  3593. also in regions already fontified."
  3594. :group 'org-appearance
  3595. :type 'boolean)
  3596. (defcustom org-hide-leading-stars nil
  3597. "Non-nil means hide the first N-1 stars in a headline.
  3598. This works by using the face `org-hide' for these stars. This
  3599. face is white for a light background, and black for a dark
  3600. background. You may have to customize the face `org-hide' to
  3601. make this work.
  3602. Changing it requires restart of `font-lock-mode' to become effective
  3603. also in regions already fontified.
  3604. You may also set this on a per-file basis by adding one of the following
  3605. lines to the buffer:
  3606. #+STARTUP: hidestars
  3607. #+STARTUP: showstars"
  3608. :group 'org-appearance
  3609. :type 'boolean)
  3610. (defcustom org-hidden-keywords nil
  3611. "List of symbols corresponding to keywords to be hidden the org buffer.
  3612. For example, a value \\='(title) for this list will make the document's title
  3613. appear in the buffer without the initial #+TITLE: keyword."
  3614. :group 'org-appearance
  3615. :version "24.1"
  3616. :type '(set (const :tag "#+AUTHOR" author)
  3617. (const :tag "#+DATE" date)
  3618. (const :tag "#+EMAIL" email)
  3619. (const :tag "#+TITLE" title)))
  3620. (defcustom org-custom-properties nil
  3621. "List of properties (as strings) with a special meaning.
  3622. The default use of these custom properties is to let the user
  3623. hide them with `org-toggle-custom-properties-visibility'."
  3624. :group 'org-properties
  3625. :group 'org-appearance
  3626. :version "24.3"
  3627. :type '(repeat (string :tag "Property Name")))
  3628. (defcustom org-fontify-done-headline nil
  3629. "Non-nil means change the face of a headline if it is marked DONE.
  3630. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3631. When this is non-nil, the headline after the keyword is set to the
  3632. `org-headline-done' as an additional indication."
  3633. :group 'org-appearance
  3634. :type 'boolean)
  3635. (defcustom org-fontify-emphasized-text t
  3636. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3637. Changing this variable requires a restart of Emacs to take effect."
  3638. :group 'org-appearance
  3639. :type 'boolean)
  3640. (defcustom org-fontify-whole-heading-line nil
  3641. "Non-nil means fontify the whole line for headings.
  3642. This is useful when setting a background color for the
  3643. org-level-* faces."
  3644. :group 'org-appearance
  3645. :type 'boolean)
  3646. (defcustom org-highlight-latex-and-related nil
  3647. "Non-nil means highlight LaTeX related syntax in the buffer.
  3648. When non nil, the value should be a list containing any of the
  3649. following symbols:
  3650. `latex' Highlight LaTeX snippets and environments.
  3651. `script' Highlight subscript and superscript.
  3652. `entities' Highlight entities."
  3653. :group 'org-appearance
  3654. :version "24.4"
  3655. :package-version '(Org . "8.0")
  3656. :type '(choice
  3657. (const :tag "No highlighting" nil)
  3658. (set :greedy t :tag "Highlight"
  3659. (const :tag "LaTeX snippets and environments" latex)
  3660. (const :tag "Subscript and superscript" script)
  3661. (const :tag "Entities" entities))))
  3662. (defcustom org-hide-emphasis-markers nil
  3663. "Non-nil mean font-lock should hide the emphasis marker characters."
  3664. :group 'org-appearance
  3665. :type 'boolean)
  3666. (defcustom org-hide-macro-markers nil
  3667. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3668. :group 'org-appearance
  3669. :type 'boolean)
  3670. (defcustom org-pretty-entities nil
  3671. "Non-nil means show entities as UTF8 characters.
  3672. When nil, the \\name form remains in the buffer."
  3673. :group 'org-appearance
  3674. :version "24.1"
  3675. :type 'boolean)
  3676. (defcustom org-pretty-entities-include-sub-superscripts t
  3677. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3678. :group 'org-appearance
  3679. :version "24.1"
  3680. :type 'boolean)
  3681. (defvar org-emph-re nil
  3682. "Regular expression for matching emphasis.
  3683. After a match, the match groups contain these elements:
  3684. 0 The match of the full regular expression, including the characters
  3685. before and after the proper match
  3686. 1 The character before the proper match, or empty at beginning of line
  3687. 2 The proper match, including the leading and trailing markers
  3688. 3 The leading marker like * or /, indicating the type of highlighting
  3689. 4 The text between the emphasis markers, not including the markers
  3690. 5 The character after the match, empty at the end of a line")
  3691. (defvar org-verbatim-re nil
  3692. "Regular expression for matching verbatim text.")
  3693. (defvar org-emphasis-regexp-components) ; defined just below
  3694. (defvar org-emphasis-alist) ; defined just below
  3695. (defun org-set-emph-re (var val)
  3696. "Set variable and compute the emphasis regular expression."
  3697. (set var val)
  3698. (when (and (boundp 'org-emphasis-alist)
  3699. (boundp 'org-emphasis-regexp-components)
  3700. org-emphasis-alist org-emphasis-regexp-components)
  3701. (let* ((e org-emphasis-regexp-components)
  3702. (pre (car e))
  3703. (post (nth 1 e))
  3704. (border (nth 2 e))
  3705. (body (nth 3 e))
  3706. (nl (nth 4 e))
  3707. (body1 (concat body "*?"))
  3708. (markers (mapconcat 'car org-emphasis-alist ""))
  3709. (vmarkers (mapconcat
  3710. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3711. org-emphasis-alist "")))
  3712. ;; make sure special characters appear at the right position in the class
  3713. (if (string-match "\\^" markers)
  3714. (setq markers (concat (replace-match "" t t markers) "^")))
  3715. (if (string-match "-" markers)
  3716. (setq markers (concat (replace-match "" t t markers) "-")))
  3717. (if (string-match "\\^" vmarkers)
  3718. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3719. (if (string-match "-" vmarkers)
  3720. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3721. (if (> nl 0)
  3722. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3723. (int-to-string nl) "\\}")))
  3724. ;; Make the regexp
  3725. (setq org-emph-re
  3726. (concat "\\([" pre "]\\|^\\)"
  3727. "\\("
  3728. "\\([" markers "]\\)"
  3729. "\\("
  3730. "[^" border "]\\|"
  3731. "[^" border "]"
  3732. body1
  3733. "[^" border "]"
  3734. "\\)"
  3735. "\\3\\)"
  3736. "\\([" post "]\\|$\\)"))
  3737. (setq org-verbatim-re
  3738. (concat "\\([" pre "]\\|^\\)"
  3739. "\\("
  3740. "\\([" vmarkers "]\\)"
  3741. "\\("
  3742. "[^" border "]\\|"
  3743. "[^" border "]"
  3744. body1
  3745. "[^" border "]"
  3746. "\\)"
  3747. "\\3\\)"
  3748. "\\([" post "]\\|$\\)")))))
  3749. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3750. ;; set this option proved cumbersome. See this message/thread:
  3751. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3752. (defvar org-emphasis-regexp-components
  3753. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3754. "Components used to build the regular expression for emphasis.
  3755. This is a list with five entries. Terminology: In an emphasis string
  3756. like \" *strong word* \", we call the initial space PREMATCH, the final
  3757. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3758. and \"trong wor\" is the body. The different components in this variable
  3759. specify what is allowed/forbidden in each part:
  3760. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3761. post Chars allowed as postmatch. End of line will be allowed too.
  3762. border The chars *forbidden* as border characters.
  3763. body-regexp A regexp like \".\" to match a body character. Don't use
  3764. non-shy groups here, and don't allow newline here.
  3765. newline The maximum number of newlines allowed in an emphasis exp.
  3766. You need to reload Org or to restart Emacs after customizing this.")
  3767. (defcustom org-emphasis-alist
  3768. `(("*" bold)
  3769. ("/" italic)
  3770. ("_" underline)
  3771. ("=" org-verbatim verbatim)
  3772. ("~" org-code verbatim)
  3773. ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
  3774. "Alist of characters and faces to emphasize text.
  3775. Text starting and ending with a special character will be emphasized,
  3776. for example *bold*, _underlined_ and /italic/. This variable sets the
  3777. marker characters and the face to be used by font-lock for highlighting
  3778. in Org-mode Emacs buffers.
  3779. You need to reload Org or to restart Emacs after customizing this."
  3780. :group 'org-appearance
  3781. :set 'org-set-emph-re
  3782. :version "24.4"
  3783. :package-version '(Org . "8.0")
  3784. :type '(repeat
  3785. (list
  3786. (string :tag "Marker character")
  3787. (choice
  3788. (face :tag "Font-lock-face")
  3789. (plist :tag "Face property list"))
  3790. (option (const verbatim)))))
  3791. (defvar org-protecting-blocks '("src" "example" "export")
  3792. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3793. This is needed for font-lock setup.")
  3794. ;;; Miscellaneous options
  3795. (defgroup org-completion nil
  3796. "Completion in Org-mode."
  3797. :tag "Org Completion"
  3798. :group 'org)
  3799. (defcustom org-completion-use-ido nil
  3800. "Non-nil means use ido completion wherever possible.
  3801. Note that `ido-mode' must be active for this variable to be relevant.
  3802. If you decide to turn this variable on, you might well want to turn off
  3803. `org-outline-path-complete-in-steps'.
  3804. See also `org-completion-use-iswitchb'."
  3805. :group 'org-completion
  3806. :type 'boolean)
  3807. (defcustom org-completion-use-iswitchb nil
  3808. "Non-nil means use iswitchb completion wherever possible.
  3809. Note that `iswitchb-mode' must be active for this variable to be relevant.
  3810. If you decide to turn this variable on, you might well want to turn off
  3811. `org-outline-path-complete-in-steps'.
  3812. Note that this variable has only an effect if `org-completion-use-ido' is nil."
  3813. :group 'org-completion
  3814. :type 'boolean)
  3815. (defcustom org-completion-fallback-command 'hippie-expand
  3816. "The expansion command called by \\[pcomplete] in normal context.
  3817. Normal means, no org-mode-specific context."
  3818. :group 'org-completion
  3819. :type 'function)
  3820. ;;; Functions and variables from their packages
  3821. ;; Declared here to avoid compiler warnings
  3822. ;; XEmacs only
  3823. (defvar outline-mode-menu-heading)
  3824. (defvar outline-mode-menu-show)
  3825. (defvar outline-mode-menu-hide)
  3826. (defvar zmacs-regions) ; XEmacs regions
  3827. ;; Emacs only
  3828. (defvar mark-active)
  3829. ;; Various packages
  3830. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3831. (declare-function calendar-forward-day "cal-move" (arg))
  3832. (declare-function calendar-goto-date "cal-move" (date))
  3833. (declare-function calendar-goto-today "cal-move" ())
  3834. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3835. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3836. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3837. (declare-function cdlatex-tab "ext:cdlatex" ())
  3838. (declare-function dired-get-filename
  3839. "dired"
  3840. (&optional localp no-error-if-not-filep))
  3841. (declare-function iswitchb-read-buffer
  3842. "iswitchb"
  3843. (prompt &optional default require-match start matches-set))
  3844. (declare-function org-agenda-change-all-lines
  3845. "org-agenda"
  3846. (newhead hdmarker &optional fixface just-this))
  3847. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3848. "org-agenda"
  3849. (&optional end))
  3850. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3851. (declare-function org-agenda-format-item
  3852. "org-agenda"
  3853. (extra txt &optional level category tags dotime noprefix
  3854. remove-re habitp))
  3855. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3856. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3857. (declare-function org-agenda-save-markers-for-cut-and-paste
  3858. "org-agenda"
  3859. (beg end))
  3860. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3861. (declare-function org-agenda-skip "org-agenda" ())
  3862. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3863. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3864. (declare-function org-indent-mode "org-indent" (&optional arg))
  3865. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3866. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3867. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3868. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3869. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3870. (declare-function parse-time-string "parse-time" (string))
  3871. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3872. (declare-function table--at-cell-p
  3873. "table"
  3874. (position &optional object at-column))
  3875. (defvar align-mode-rules-list)
  3876. (defvar calc-embedded-close-formula)
  3877. (defvar calc-embedded-open-formula)
  3878. (defvar calc-embedded-open-mode)
  3879. (defvar font-lock-unfontify-region-function)
  3880. (defvar iswitchb-temp-buflist)
  3881. (defvar org-agenda-tags-todo-honor-ignore-options)
  3882. (defvar remember-data-file)
  3883. (defvar texmathp-why)
  3884. ;;;###autoload
  3885. (defun turn-on-orgtbl ()
  3886. "Unconditionally turn on `orgtbl-mode'."
  3887. (require 'org-table)
  3888. (orgtbl-mode 1))
  3889. (defun org-at-table-p (&optional table-type)
  3890. "Non-nil if the cursor is inside an Org table.
  3891. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3892. If `org-enable-table-editor' is nil, return nil unconditionally."
  3893. (and
  3894. org-enable-table-editor
  3895. (save-excursion
  3896. (beginning-of-line)
  3897. (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3898. (or (not (derived-mode-p 'org-mode))
  3899. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3900. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3901. (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
  3902. (defun org-at-table.el-p ()
  3903. "Non-nil when point is at a table.el table."
  3904. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3905. (let ((element (org-element-at-point)))
  3906. (and (eq (org-element-type element) 'table)
  3907. (eq (org-element-property :type element) 'table.el)))))
  3908. (defun org-table-recognize-table.el ()
  3909. "If there is a table.el table nearby, recognize it and move into it."
  3910. (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
  3911. (beginning-of-line)
  3912. (unless (or (looking-at org-table-dataline-regexp)
  3913. (not (looking-at org-table1-hline-regexp)))
  3914. (forward-line)
  3915. (when (looking-at org-table-any-border-regexp)
  3916. (forward-line -2)))
  3917. (if (re-search-forward "|" (org-table-end t) t)
  3918. (progn
  3919. (require 'table)
  3920. (if (table--at-cell-p (point)) t
  3921. (message "recognizing table.el table...")
  3922. (table-recognize-table)
  3923. (message "recognizing table.el table...done")))
  3924. (error "This should not happen"))))
  3925. ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
  3926. (make-obsolete 'org-table-recognize-table.el
  3927. "please notify the org mailing list if you use this function."
  3928. "Org 9.0")
  3929. (defun org-at-table-hline-p ()
  3930. "Non-nil when point is inside a hline in a table.
  3931. Assume point is already in a table. If `org-enable-table-editor'
  3932. is nil, return nil unconditionally."
  3933. (and org-enable-table-editor
  3934. (save-excursion
  3935. (beginning-of-line)
  3936. (looking-at org-table-hline-regexp))))
  3937. (defun org-table-map-tables (function &optional quietly)
  3938. "Apply FUNCTION to the start of all tables in the buffer."
  3939. (save-excursion
  3940. (save-restriction
  3941. (widen)
  3942. (goto-char (point-min))
  3943. (while (re-search-forward org-table-any-line-regexp nil t)
  3944. (unless quietly
  3945. (message "Mapping tables: %d%%"
  3946. (floor (* 100.0 (point)) (buffer-size))))
  3947. (beginning-of-line 1)
  3948. (when (and (looking-at org-table-line-regexp)
  3949. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3950. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3951. (save-excursion (funcall function))
  3952. (or (looking-at org-table-line-regexp)
  3953. (forward-char 1)))
  3954. (re-search-forward org-table-any-border-regexp nil 1))))
  3955. (unless quietly (message "Mapping tables: done")))
  3956. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3957. (declare-function org-clock-update-mode-line "org-clock" ())
  3958. (declare-function org-resolve-clocks "org-clock"
  3959. (&optional also-non-dangling-p prompt last-valid))
  3960. (defun org-at-TBLFM-p (&optional pos)
  3961. "Non-nil when point (or POS) is in #+TBLFM line."
  3962. (save-excursion
  3963. (goto-char (or pos (point)))
  3964. (beginning-of-line)
  3965. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3966. (eq (org-element-type (org-element-at-point)) 'table))))
  3967. (defvar org-clock-start-time)
  3968. (defvar org-clock-marker (make-marker)
  3969. "Marker recording the last clock-in.")
  3970. (defvar org-clock-hd-marker (make-marker)
  3971. "Marker recording the last clock-in, but the headline position.")
  3972. (defvar org-clock-heading ""
  3973. "The heading of the current clock entry.")
  3974. (defun org-clock-is-active ()
  3975. "Return the buffer where the clock is currently running.
  3976. Return nil if no clock is running."
  3977. (marker-buffer org-clock-marker))
  3978. (defun org-check-running-clock ()
  3979. "Check if the current buffer contains the running clock.
  3980. If yes, offer to stop it and to save the buffer with the changes."
  3981. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3982. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3983. (buffer-name))))
  3984. (org-clock-out)
  3985. (when (y-or-n-p "Save changed buffer?")
  3986. (save-buffer))))
  3987. (defun org-clocktable-try-shift (dir n)
  3988. "Check if this line starts a clock table, if yes, shift the time block."
  3989. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3990. (org-clocktable-shift dir n)))
  3991. ;;;###autoload
  3992. (defun org-clock-persistence-insinuate ()
  3993. "Set up hooks for clock persistence."
  3994. (require 'org-clock)
  3995. (add-hook 'org-mode-hook 'org-clock-load)
  3996. (add-hook 'kill-emacs-hook 'org-clock-save))
  3997. (defgroup org-archive nil
  3998. "Options concerning archiving in Org-mode."
  3999. :tag "Org Archive"
  4000. :group 'org-structure)
  4001. (defcustom org-archive-location "%s_archive::"
  4002. "The location where subtrees should be archived.
  4003. The value of this variable is a string, consisting of two parts,
  4004. separated by a double-colon. The first part is a filename and
  4005. the second part is a headline.
  4006. When the filename is omitted, archiving happens in the same file.
  4007. %s in the filename will be replaced by the current file
  4008. name (without the directory part). Archiving to a different file
  4009. is useful to keep archived entries from contributing to the
  4010. Org-mode Agenda.
  4011. The archived entries will be filed as subtrees of the specified
  4012. headline. When the headline is omitted, the subtrees are simply
  4013. filed away at the end of the file, as top-level entries. Also in
  4014. the heading you can use %s to represent the file name, this can be
  4015. useful when using the same archive for a number of different files.
  4016. Here are a few examples:
  4017. \"%s_archive::\"
  4018. If the current file is Projects.org, archive in file
  4019. Projects.org_archive, as top-level trees. This is the default.
  4020. \"::* Archived Tasks\"
  4021. Archive in the current file, under the top-level headline
  4022. \"* Archived Tasks\".
  4023. \"~/org/archive.org::\"
  4024. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4025. \"~/org/archive.org::* From %s\"
  4026. Archive in file ~/org/archive.org (absolute path), under headlines
  4027. \"From FILENAME\" where file name is the current file name.
  4028. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4029. The \"datetree/\" string is special, signifying to archive
  4030. items to the datetree. Items are placed in either the CLOSED
  4031. date of the item, or the current date if there is no CLOSED date.
  4032. The heading will be a subentry to the current date. There doesn't
  4033. need to be a heading, but there always needs to be a slash after
  4034. datetree. For example, to store archived items directly in the
  4035. datetree, use \"~/org/datetree.org::datetree/\".
  4036. \"basement::** Finished Tasks\"
  4037. Archive in file ./basement (relative path), as level 3 trees
  4038. below the level 2 heading \"** Finished Tasks\".
  4039. You may set this option on a per-file basis by adding to the buffer a
  4040. line like
  4041. #+ARCHIVE: basement::** Finished Tasks
  4042. You may also define it locally for a subtree by setting an ARCHIVE property
  4043. in the entry. If such a property is found in an entry, or anywhere up
  4044. the hierarchy, it will be used."
  4045. :group 'org-archive
  4046. :type 'string)
  4047. (defcustom org-agenda-skip-archived-trees t
  4048. "Non-nil means the agenda will skip any items located in archived trees.
  4049. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4050. variable is no longer recommended, you should leave it at the value t.
  4051. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4052. :group 'org-archive
  4053. :group 'org-agenda-skip
  4054. :type 'boolean)
  4055. (defcustom org-columns-skip-archived-trees t
  4056. "Non-nil means ignore archived trees when creating column view."
  4057. :group 'org-archive
  4058. :group 'org-properties
  4059. :type 'boolean)
  4060. (defcustom org-cycle-open-archived-trees nil
  4061. "Non-nil means `org-cycle' will open archived trees.
  4062. An archived tree is a tree marked with the tag ARCHIVE.
  4063. When nil, archived trees will stay folded. You can still open them with
  4064. normal outline commands like `show-all', but not with the cycling commands."
  4065. :group 'org-archive
  4066. :group 'org-cycle
  4067. :type 'boolean)
  4068. (defcustom org-sparse-tree-open-archived-trees nil
  4069. "Non-nil means sparse tree construction shows matches in archived trees.
  4070. When nil, matches in these trees are highlighted, but the trees are kept in
  4071. collapsed state."
  4072. :group 'org-archive
  4073. :group 'org-sparse-trees
  4074. :type 'boolean)
  4075. (defcustom org-sparse-tree-default-date-type nil
  4076. "The default date type when building a sparse tree.
  4077. When this is nil, a date is a scheduled or a deadline timestamp.
  4078. Otherwise, these types are allowed:
  4079. all: all timestamps
  4080. active: only active timestamps (<...>)
  4081. inactive: only inactive timestamps ([...])
  4082. scheduled: only scheduled timestamps
  4083. deadline: only deadline timestamps"
  4084. :type '(choice (const :tag "Scheduled or deadline" nil)
  4085. (const :tag "All timestamps" all)
  4086. (const :tag "Only active timestamps" active)
  4087. (const :tag "Only inactive timestamps" inactive)
  4088. (const :tag "Only scheduled timestamps" scheduled)
  4089. (const :tag "Only deadline timestamps" deadline)
  4090. (const :tag "Only closed timestamps" closed))
  4091. :version "25.1"
  4092. :package-version '(Org . "8.3")
  4093. :group 'org-sparse-trees)
  4094. (defun org-cycle-hide-archived-subtrees (state)
  4095. "Re-hide all archived subtrees after a visibility state change."
  4096. (when (and (not org-cycle-open-archived-trees)
  4097. (not (memq state '(overview folded))))
  4098. (save-excursion
  4099. (let* ((globalp (memq state '(contents all)))
  4100. (beg (if globalp (point-min) (point)))
  4101. (end (if globalp (point-max) (org-end-of-subtree t))))
  4102. (org-hide-archived-subtrees beg end)
  4103. (goto-char beg)
  4104. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4105. (message "%s" (substitute-command-keys
  4106. "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
  4107. (defun org-force-cycle-archived ()
  4108. "Cycle subtree even if it is archived."
  4109. (interactive)
  4110. (setq this-command 'org-cycle)
  4111. (let ((org-cycle-open-archived-trees t))
  4112. (call-interactively 'org-cycle)))
  4113. (defun org-hide-archived-subtrees (beg end)
  4114. "Re-hide all archived subtrees after a visibility state change."
  4115. (org-with-wide-buffer
  4116. (let ((case-fold-search nil)
  4117. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4118. (goto-char beg)
  4119. ;; Include headline point is currently on.
  4120. (beginning-of-line)
  4121. (while (and (< (point) end) (re-search-forward re end t))
  4122. (when (member org-archive-tag (org-get-tags))
  4123. (org-flag-subtree t)
  4124. (org-end-of-subtree t))))))
  4125. (declare-function outline-end-of-heading "outline" ())
  4126. (declare-function outline-flag-region "outline" (from to flag))
  4127. (defun org-flag-subtree (flag)
  4128. (save-excursion
  4129. (org-back-to-heading t)
  4130. (outline-end-of-heading)
  4131. (outline-flag-region (point)
  4132. (progn (org-end-of-subtree t) (point))
  4133. flag)))
  4134. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4135. ;; Declare Column View Code
  4136. (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
  4137. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4138. (declare-function org-columns-compute "org-colview" (property))
  4139. ;; Declare ID code
  4140. (declare-function org-id-store-link "org-id")
  4141. (declare-function org-id-locations-load "org-id")
  4142. (declare-function org-id-locations-save "org-id")
  4143. (defvar org-id-track-globally)
  4144. ;;; Variables for pre-computed regular expressions, all buffer local
  4145. (defvar-local org-todo-regexp nil
  4146. "Matches any of the TODO state keywords.")
  4147. (defvar-local org-not-done-regexp nil
  4148. "Matches any of the TODO state keywords except the last one.")
  4149. (defvar-local org-not-done-heading-regexp nil
  4150. "Matches a TODO headline that is not done.")
  4151. (defvar-local org-todo-line-regexp nil
  4152. "Matches a headline and puts TODO state into group 2 if present.")
  4153. (defvar-local org-complex-heading-regexp nil
  4154. "Matches a headline and puts everything into groups:
  4155. group 1: the stars
  4156. group 2: The todo keyword, maybe
  4157. group 3: Priority cookie
  4158. group 4: True headline
  4159. group 5: Tags")
  4160. (defvar-local org-complex-heading-regexp-format nil
  4161. "Printf format to make regexp to match an exact headline.
  4162. This regexp will match the headline of any node which has the
  4163. exact headline text that is put into the format, but may have any
  4164. TODO state, priority and tags.")
  4165. (defvar-local org-todo-line-tags-regexp nil
  4166. "Matches a headline and puts TODO state into group 2 if present.
  4167. Also put tags into group 4 if tags are present.")
  4168. (defconst org-plain-time-of-day-regexp
  4169. (concat
  4170. "\\(\\<[012]?[0-9]"
  4171. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4172. "\\(--?"
  4173. "\\(\\<[012]?[0-9]"
  4174. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4175. "\\)?")
  4176. "Regular expression to match a plain time or time range.
  4177. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4178. groups carry important information:
  4179. 0 the full match
  4180. 1 the first time, range or not
  4181. 8 the second time, if it is a range.")
  4182. (defconst org-plain-time-extension-regexp
  4183. (concat
  4184. "\\(\\<[012]?[0-9]"
  4185. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4186. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4187. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4188. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4189. groups carry important information:
  4190. 0 the full match
  4191. 7 hours of duration
  4192. 9 minutes of duration")
  4193. (defconst org-stamp-time-of-day-regexp
  4194. (concat
  4195. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4196. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4197. "\\(--?"
  4198. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4199. "Regular expression to match a timestamp time or time range.
  4200. After a match, the following groups carry important information:
  4201. 0 the full match
  4202. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4203. 2 the first time, range or not
  4204. 4 the second time, if it is a range.")
  4205. (defconst org-startup-options
  4206. '(("fold" org-startup-folded t)
  4207. ("overview" org-startup-folded t)
  4208. ("nofold" org-startup-folded nil)
  4209. ("showall" org-startup-folded nil)
  4210. ("showeverything" org-startup-folded showeverything)
  4211. ("content" org-startup-folded content)
  4212. ("indent" org-startup-indented t)
  4213. ("noindent" org-startup-indented nil)
  4214. ("hidestars" org-hide-leading-stars t)
  4215. ("showstars" org-hide-leading-stars nil)
  4216. ("odd" org-odd-levels-only t)
  4217. ("oddeven" org-odd-levels-only nil)
  4218. ("align" org-startup-align-all-tables t)
  4219. ("noalign" org-startup-align-all-tables nil)
  4220. ("inlineimages" org-startup-with-inline-images t)
  4221. ("noinlineimages" org-startup-with-inline-images nil)
  4222. ("latexpreview" org-startup-with-latex-preview t)
  4223. ("nolatexpreview" org-startup-with-latex-preview nil)
  4224. ("customtime" org-display-custom-times t)
  4225. ("logdone" org-log-done time)
  4226. ("lognotedone" org-log-done note)
  4227. ("nologdone" org-log-done nil)
  4228. ("lognoteclock-out" org-log-note-clock-out t)
  4229. ("nolognoteclock-out" org-log-note-clock-out nil)
  4230. ("logrepeat" org-log-repeat state)
  4231. ("lognoterepeat" org-log-repeat note)
  4232. ("logdrawer" org-log-into-drawer t)
  4233. ("nologdrawer" org-log-into-drawer nil)
  4234. ("logstatesreversed" org-log-states-order-reversed t)
  4235. ("nologstatesreversed" org-log-states-order-reversed nil)
  4236. ("nologrepeat" org-log-repeat nil)
  4237. ("logreschedule" org-log-reschedule time)
  4238. ("lognotereschedule" org-log-reschedule note)
  4239. ("nologreschedule" org-log-reschedule nil)
  4240. ("logredeadline" org-log-redeadline time)
  4241. ("lognoteredeadline" org-log-redeadline note)
  4242. ("nologredeadline" org-log-redeadline nil)
  4243. ("logrefile" org-log-refile time)
  4244. ("lognoterefile" org-log-refile note)
  4245. ("nologrefile" org-log-refile nil)
  4246. ("fninline" org-footnote-define-inline t)
  4247. ("nofninline" org-footnote-define-inline nil)
  4248. ("fnlocal" org-footnote-section nil)
  4249. ("fnauto" org-footnote-auto-label t)
  4250. ("fnprompt" org-footnote-auto-label nil)
  4251. ("fnconfirm" org-footnote-auto-label confirm)
  4252. ("fnplain" org-footnote-auto-label plain)
  4253. ("fnadjust" org-footnote-auto-adjust t)
  4254. ("nofnadjust" org-footnote-auto-adjust nil)
  4255. ("constcgs" constants-unit-system cgs)
  4256. ("constSI" constants-unit-system SI)
  4257. ("noptag" org-tag-persistent-alist nil)
  4258. ("hideblocks" org-hide-block-startup t)
  4259. ("nohideblocks" org-hide-block-startup nil)
  4260. ("beamer" org-startup-with-beamer-mode t)
  4261. ("entitiespretty" org-pretty-entities t)
  4262. ("entitiesplain" org-pretty-entities nil))
  4263. "Variable associated with STARTUP options for org-mode.
  4264. Each element is a list of three items: the startup options (as written
  4265. in the #+STARTUP line), the corresponding variable, and the value to set
  4266. this variable to if the option is found. An optional forth element PUSH
  4267. means to push this value onto the list in the variable.")
  4268. (defcustom org-group-tags t
  4269. "When non-nil (the default), use group tags.
  4270. This can be turned on/off through `org-toggle-tags-groups'."
  4271. :group 'org-tags
  4272. :group 'org-startup
  4273. :type 'boolean)
  4274. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4275. (defun org-toggle-tags-groups ()
  4276. "Toggle support for group tags.
  4277. Support for group tags is controlled by the option
  4278. `org-group-tags', which is non-nil by default."
  4279. (interactive)
  4280. (setq org-group-tags (not org-group-tags))
  4281. (cond ((and (derived-mode-p 'org-agenda-mode)
  4282. org-group-tags)
  4283. (org-agenda-redo))
  4284. ((derived-mode-p 'org-mode)
  4285. (let ((org-inhibit-startup t)) (org-mode))))
  4286. (message "Groups tags support has been turned %s"
  4287. (if org-group-tags "on" "off")))
  4288. (defun org-set-regexps-and-options (&optional tags-only)
  4289. "Precompute regular expressions used in the current buffer.
  4290. When optional argument TAGS-ONLY is non-nil, only compute tags
  4291. related expressions."
  4292. (when (derived-mode-p 'org-mode)
  4293. (let ((alist (org--setup-collect-keywords
  4294. (org-make-options-regexp
  4295. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4296. (and (not tags-only)
  4297. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4298. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4299. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4300. (org--setup-process-tags
  4301. (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
  4302. (unless tags-only
  4303. ;; File properties.
  4304. (setq-local org-file-properties (cdr (assq 'property alist)))
  4305. ;; Archive location.
  4306. (let ((archive (cdr (assq 'archive alist))))
  4307. (when archive (setq-local org-archive-location archive)))
  4308. ;; Category.
  4309. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4310. (when cat
  4311. (setq-local org-category (intern cat))
  4312. (setq-local org-file-properties
  4313. (org--update-property-plist
  4314. "CATEGORY" cat org-file-properties))))
  4315. ;; Columns.
  4316. (let ((column (cdr (assq 'columns alist))))
  4317. (when column (setq-local org-columns-default-format column)))
  4318. ;; Constants.
  4319. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4320. ;; Link abbreviations.
  4321. (let ((links (cdr (assq 'link alist))))
  4322. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4323. ;; Priorities.
  4324. (let ((priorities (cdr (assq 'priorities alist))))
  4325. (when priorities
  4326. (setq-local org-highest-priority (nth 0 priorities))
  4327. (setq-local org-lowest-priority (nth 1 priorities))
  4328. (setq-local org-default-priority (nth 2 priorities))))
  4329. ;; Scripts.
  4330. (let ((scripts (assq 'scripts alist)))
  4331. (when scripts
  4332. (setq-local org-use-sub-superscripts (cdr scripts))))
  4333. ;; Startup options.
  4334. (let ((startup (cdr (assq 'startup alist))))
  4335. (dolist (option startup)
  4336. (let ((entry (assoc-string option org-startup-options t)))
  4337. (when entry
  4338. (let ((var (nth 1 entry))
  4339. (val (nth 2 entry)))
  4340. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4341. (unless (listp (symbol-value var))
  4342. (set (make-local-variable var) nil))
  4343. (add-to-list var val)))))))
  4344. ;; TODO keywords.
  4345. (setq-local org-todo-kwd-alist nil)
  4346. (setq-local org-todo-key-alist nil)
  4347. (setq-local org-todo-key-trigger nil)
  4348. (setq-local org-todo-keywords-1 nil)
  4349. (setq-local org-done-keywords nil)
  4350. (setq-local org-todo-heads nil)
  4351. (setq-local org-todo-sets nil)
  4352. (setq-local org-todo-log-states nil)
  4353. (let ((todo-sequences
  4354. (or (nreverse (cdr (assq 'todo alist)))
  4355. (let ((d (default-value 'org-todo-keywords)))
  4356. (if (not (stringp (car d))) d
  4357. ;; XXX: Backward compatibility code.
  4358. (list (cons org-todo-interpretation d)))))))
  4359. (dolist (sequence todo-sequences)
  4360. (let* ((sequence (or (run-hook-with-args-until-success
  4361. 'org-todo-setup-filter-hook sequence)
  4362. sequence))
  4363. (sequence-type (car sequence))
  4364. (keywords (cdr sequence))
  4365. (sep (member "|" keywords))
  4366. names alist)
  4367. (dolist (k (remove "|" keywords))
  4368. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4369. k)
  4370. (error "Invalid TODO keyword %s" k))
  4371. (let ((name (match-string 1 k))
  4372. (key (match-string 2 k))
  4373. (log (org-extract-log-state-settings k)))
  4374. (push name names)
  4375. (push (cons name (and key (string-to-char key))) alist)
  4376. (when log (push log org-todo-log-states))))
  4377. (let* ((names (nreverse names))
  4378. (done (if sep (org-remove-keyword-keys (cdr sep))
  4379. (last names)))
  4380. (head (car names))
  4381. (tail (list sequence-type head (car done) (org-last done))))
  4382. (add-to-list 'org-todo-heads head 'append)
  4383. (push names org-todo-sets)
  4384. (setq org-done-keywords (append org-done-keywords done nil))
  4385. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4386. (setq org-todo-key-alist
  4387. (append org-todo-key-alist
  4388. (and alist
  4389. (append '((:startgroup))
  4390. (nreverse alist)
  4391. '((:endgroup))))))
  4392. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4393. (setq org-todo-sets (nreverse org-todo-sets)
  4394. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4395. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4396. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4397. ;; Compute the regular expressions and other local variables.
  4398. ;; Using `org-outline-regexp-bol' would complicate them much,
  4399. ;; because of the fixed white space at the end of that string.
  4400. (unless org-done-keywords
  4401. (setq org-done-keywords
  4402. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4403. (setq org-not-done-keywords
  4404. (org-delete-all org-done-keywords
  4405. (copy-sequence org-todo-keywords-1))
  4406. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4407. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4408. org-not-done-heading-regexp
  4409. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4410. org-todo-line-regexp
  4411. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4412. org-complex-heading-regexp
  4413. (concat "^\\(\\*+\\)"
  4414. "\\(?: +" org-todo-regexp "\\)?"
  4415. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4416. "\\(?: +\\(.*?\\)\\)??"
  4417. (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
  4418. "[ \t]*$")
  4419. org-complex-heading-regexp-format
  4420. (concat "^\\(\\*+\\)"
  4421. "\\(?: +" org-todo-regexp "\\)?"
  4422. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4423. "\\(?: +"
  4424. ;; Stats cookies can be stuck to body.
  4425. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4426. "\\(%s\\)"
  4427. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4428. "\\)"
  4429. (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
  4430. "[ \t]*$")
  4431. org-todo-line-tags-regexp
  4432. (concat "^\\(\\*+\\)"
  4433. "\\(?: +" org-todo-regexp "\\)?"
  4434. "\\(?: +\\(.*?\\)\\)??"
  4435. (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
  4436. "[ \t]*$"))
  4437. (org-compute-latex-and-related-regexp)))))
  4438. (defun org--setup-collect-keywords (regexp &optional files alist)
  4439. "Return setup keywords values as an alist.
  4440. REGEXP matches a subset of setup keywords. FILES is a list of
  4441. file names already visited. It is used to avoid circular setup
  4442. files. ALIST, when non-nil, is the alist computed so far.
  4443. Return value contains the following keys: `archive', `category',
  4444. `columns', `constants', `filetags', `link', `priorities',
  4445. `property', `scripts', `startup', `tags' and `todo'."
  4446. (org-with-wide-buffer
  4447. (goto-char (point-min))
  4448. (let ((case-fold-search t))
  4449. (while (re-search-forward regexp nil t)
  4450. (let ((element (org-element-at-point)))
  4451. (when (eq (org-element-type element) 'keyword)
  4452. (let ((key (org-element-property :key element))
  4453. (value (org-element-property :value element)))
  4454. (cond
  4455. ((equal key "ARCHIVE")
  4456. (when (org-string-nw-p value)
  4457. (push (cons 'archive value) alist)))
  4458. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4459. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4460. ((equal key "CONSTANTS")
  4461. (let* ((constants (assq 'constants alist))
  4462. (store (cdr constants)))
  4463. (dolist (pair (org-split-string value))
  4464. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4465. pair)
  4466. (let* ((name (match-string 1 pair))
  4467. (value (match-string 2 pair))
  4468. (old (assoc name store)))
  4469. (if old (setcdr old value)
  4470. (push (cons name value) store)))))
  4471. (if constants (setcdr constants store)
  4472. (push (cons 'constants store) alist))))
  4473. ((equal key "FILETAGS")
  4474. (when (org-string-nw-p value)
  4475. (let ((old (assq 'filetags alist))
  4476. (new (apply #'nconc
  4477. (mapcar (lambda (x) (org-split-string x ":"))
  4478. (org-split-string value)))))
  4479. (if old (setcdr old (append new (cdr old)))
  4480. (push (cons 'filetags new) alist)))))
  4481. ((equal key "LINK")
  4482. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4483. (let ((links (assq 'link alist))
  4484. (pair (cons (org-match-string-no-properties 1 value)
  4485. (org-match-string-no-properties 2 value))))
  4486. (if links (push pair (cdr links))
  4487. (push (list 'link pair) alist)))))
  4488. ((equal key "OPTIONS")
  4489. (when (and (org-string-nw-p value)
  4490. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4491. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4492. ((equal key "PRIORITIES")
  4493. (push (cons 'priorities
  4494. (let ((prio (org-split-string value)))
  4495. (if (< (length prio) 3) '(?A ?C ?B)
  4496. (mapcar #'string-to-char prio))))
  4497. alist))
  4498. ((equal key "PROPERTY")
  4499. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4500. (let* ((property (assq 'property alist))
  4501. (value (org--update-property-plist
  4502. (org-match-string-no-properties 1 value)
  4503. (org-match-string-no-properties 2 value)
  4504. (cdr property))))
  4505. (if property (setcdr property value)
  4506. (push (cons 'property value) alist)))))
  4507. ((equal key "STARTUP")
  4508. (let ((startup (assq 'startup alist)))
  4509. (if startup
  4510. (setcdr startup
  4511. (append (cdr startup) (org-split-string value)))
  4512. (push (cons 'startup (org-split-string value)) alist))))
  4513. ((equal key "TAGS")
  4514. (let ((tag-cell (assq 'tags alist)))
  4515. (if tag-cell
  4516. (setcdr tag-cell
  4517. (append (cdr tag-cell)
  4518. '("\\n")
  4519. (org-split-string value)))
  4520. (push (cons 'tags (org-split-string value)) alist))))
  4521. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4522. (let ((todo (assq 'todo alist))
  4523. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4524. (org-split-string value))))
  4525. (if todo (push value (cdr todo))
  4526. (push (list 'todo value) alist))))
  4527. ((equal key "SETUPFILE")
  4528. (unless buffer-read-only ; Do not check in Gnus messages.
  4529. (let ((f (and (org-string-nw-p value)
  4530. (expand-file-name
  4531. (org-remove-double-quotes value)))))
  4532. (when (and f (file-readable-p f) (not (member f files)))
  4533. (with-temp-buffer
  4534. (setq default-directory (file-name-directory f))
  4535. (insert-file-contents f)
  4536. (setq alist
  4537. ;; Fake Org mode to benefit from cache
  4538. ;; without recurring needlessly.
  4539. (let ((major-mode 'org-mode))
  4540. (org--setup-collect-keywords
  4541. regexp (cons f files) alist)))))))))))))))
  4542. alist)
  4543. (defun org--setup-process-tags (tags filetags)
  4544. "Precompute variables used for tags.
  4545. TAGS is a list of tags and tag group symbols, as strings.
  4546. FILETAGS is a list of tags, as strings."
  4547. ;; Process the file tags.
  4548. (setq-local org-file-tags
  4549. (mapcar #'org-add-prop-inherited filetags))
  4550. ;; Provide default tags if no local tags are found.
  4551. (when (and (not tags) org-tag-alist)
  4552. (setq tags
  4553. (mapcar (lambda (tag)
  4554. (case (car tag)
  4555. (:startgroup "{")
  4556. (:endgroup "}")
  4557. (:startgrouptag "[")
  4558. (:endgrouptag "]")
  4559. (:grouptags ":")
  4560. (:newline "\\n")
  4561. (otherwise (concat (car tag)
  4562. (and (characterp (cdr tag))
  4563. (format "(%c)" (cdr tag)))))))
  4564. org-tag-alist)))
  4565. ;; Process the tags.
  4566. (setq-local org-tag-groups-alist nil)
  4567. (setq-local org-tag-alist nil)
  4568. (let (group-flag)
  4569. (while tags
  4570. (let ((e (car tags)))
  4571. (setq tags (cdr tags))
  4572. (cond
  4573. ((equal e "{")
  4574. (push '(:startgroup) org-tag-alist)
  4575. (when (equal (nth 1 tags) ":") (setq group-flag t)))
  4576. ((equal e "}")
  4577. (push '(:endgroup) org-tag-alist)
  4578. (setq group-flag nil))
  4579. ((equal e "[")
  4580. (push '(:startgrouptag) org-tag-alist)
  4581. (when (equal (nth 1 tags) ":") (setq group-flag t)))
  4582. ((equal e "]")
  4583. (push '(:endgrouptag) org-tag-alist)
  4584. (setq group-flag nil))
  4585. ((equal e ":")
  4586. (push '(:grouptags) org-tag-alist)
  4587. (setq group-flag 'append))
  4588. ((equal e "\\n") (push '(:newline) org-tag-alist))
  4589. ((string-match
  4590. (org-re (concat "\\`\\([[:alnum:]_@#%]+"
  4591. "\\|{.+?}\\)" ; regular expression
  4592. "\\(?:(\\(.\\))\\)?\\'")) e)
  4593. (let ((tag (match-string 1 e))
  4594. (key (and (match-beginning 2)
  4595. (string-to-char (match-string 2 e)))))
  4596. (cond ((eq group-flag 'append)
  4597. (setcar org-tag-groups-alist
  4598. (append (car org-tag-groups-alist) (list tag))))
  4599. (group-flag (push (list tag) org-tag-groups-alist)))
  4600. ;; Push all tags in groups, no matter if they already exist.
  4601. (unless (and (not group-flag) (assoc tag org-tag-alist))
  4602. (push (cons tag key) org-tag-alist))))))))
  4603. (setq org-tag-alist (nreverse org-tag-alist)))
  4604. (defun org-file-contents (file &optional noerror)
  4605. "Return the contents of FILE, as a string."
  4606. (if (and file (file-readable-p file))
  4607. (with-temp-buffer
  4608. (insert-file-contents file)
  4609. (buffer-string))
  4610. (funcall (if noerror 'message 'error)
  4611. "Cannot read file \"%s\"%s"
  4612. file
  4613. (let ((from (buffer-file-name (buffer-base-buffer))))
  4614. (if from (concat " (referenced in file \"" from "\")") "")))))
  4615. (defun org-extract-log-state-settings (x)
  4616. "Extract the log state setting from a TODO keyword string.
  4617. This will extract info from a string like \"WAIT(w@/!)\"."
  4618. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4619. (let ((kw (match-string 1 x))
  4620. (log1 (and (match-end 3) (match-string 3 x)))
  4621. (log2 (and (match-end 4) (match-string 4 x))))
  4622. (and (or log1 log2)
  4623. (list kw
  4624. (and log1 (if (equal log1 "!") 'time 'note))
  4625. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4626. (defun org-remove-keyword-keys (list)
  4627. "Remove a pair of parenthesis at the end of each string in LIST."
  4628. (mapcar (lambda (x)
  4629. (if (string-match "(.*)$" x)
  4630. (substring x 0 (match-beginning 0))
  4631. x))
  4632. list))
  4633. (defun org-assign-fast-keys (alist)
  4634. "Assign fast keys to a keyword-key alist.
  4635. Respect keys that are already there."
  4636. (let (new e (alt ?0))
  4637. (while (setq e (pop alist))
  4638. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4639. (cdr e)) ;; Key already assigned.
  4640. (push e new)
  4641. (let ((clist (string-to-list (downcase (car e))))
  4642. (used (append new alist)))
  4643. (when (= (car clist) ?@)
  4644. (pop clist))
  4645. (while (and clist (rassoc (car clist) used))
  4646. (pop clist))
  4647. (unless clist
  4648. (while (rassoc alt used)
  4649. (incf alt)))
  4650. (push (cons (car e) (or (car clist) alt)) new))))
  4651. (nreverse new)))
  4652. ;;; Some variables used in various places
  4653. (defvar org-window-configuration nil
  4654. "Used in various places to store a window configuration.")
  4655. (defvar org-selected-window nil
  4656. "Used in various places to store a window configuration.")
  4657. (defvar org-finish-function nil
  4658. "Function to be called when `C-c C-c' is used.
  4659. This is for getting out of special buffers like capture.")
  4660. (defvar org-last-state)
  4661. ;; Defined somewhere in this file, but used before definition.
  4662. (defvar org-entities) ;; defined in org-entities.el
  4663. (defvar org-struct-menu)
  4664. (defvar org-org-menu)
  4665. (defvar org-tbl-menu)
  4666. ;;;; Define the Org-mode
  4667. ;; We use a before-change function to check if a table might need
  4668. ;; an update.
  4669. (defvar org-table-may-need-update t
  4670. "Indicates that a table might need an update.
  4671. This variable is set by `org-before-change-function'.
  4672. `org-table-align' sets it back to nil.")
  4673. (defun org-before-change-function (_beg _end)
  4674. "Every change indicates that a table might need an update."
  4675. (setq org-table-may-need-update t))
  4676. (defvar org-mode-map)
  4677. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4678. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4679. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4680. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4681. (defvar org-table-buffer-is-an nil)
  4682. (defvar bidi-paragraph-direction)
  4683. (defvar buffer-face-mode-face)
  4684. (require 'outline)
  4685. (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
  4686. (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
  4687. (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
  4688. ;; Other stuff we need.
  4689. (require 'time-date)
  4690. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4691. (require 'easymenu)
  4692. (autoload 'easy-menu-add "easymenu")
  4693. (require 'overlay)
  4694. ;; (require 'org-macs) moved higher up in the file before it is first used
  4695. (require 'org-entities)
  4696. ;; (require 'org-compat) moved higher up in the file before it is first used
  4697. (require 'org-faces)
  4698. (require 'org-list)
  4699. (require 'org-pcomplete)
  4700. (require 'org-src)
  4701. (require 'org-footnote)
  4702. (require 'org-macro)
  4703. ;; babel
  4704. (require 'ob)
  4705. ;;;###autoload
  4706. (define-derived-mode org-mode outline-mode "Org"
  4707. "Outline-based notes management and organizer, alias
  4708. \"Carsten's outline-mode for keeping track of everything.\"
  4709. Org-mode develops organizational tasks around a NOTES file which
  4710. contains information about projects as plain text. Org-mode is
  4711. implemented on top of outline-mode, which is ideal to keep the content
  4712. of large files well structured. It supports ToDo items, deadlines and
  4713. time stamps, which magically appear in the diary listing of the Emacs
  4714. calendar. Tables are easily created with a built-in table editor.
  4715. Plain text URL-like links connect to websites, emails (VM), Usenet
  4716. messages (Gnus), BBDB entries, and any files related to the project.
  4717. For printing and sharing of notes, an Org-mode file (or a part of it)
  4718. can be exported as a structured ASCII or HTML file.
  4719. The following commands are available:
  4720. \\{org-mode-map}"
  4721. ;; Get rid of Outline menus, they are not needed
  4722. ;; Need to do this here because define-derived-mode sets up
  4723. ;; the keymap so late. Still, it is a waste to call this each time
  4724. ;; we switch another buffer into org-mode.
  4725. (if (featurep 'xemacs)
  4726. (when (boundp 'outline-mode-menu-heading)
  4727. ;; Assume this is Greg's port, it uses easymenu
  4728. (easy-menu-remove outline-mode-menu-heading)
  4729. (easy-menu-remove outline-mode-menu-show)
  4730. (easy-menu-remove outline-mode-menu-hide))
  4731. (define-key org-mode-map [menu-bar headings] 'undefined)
  4732. (define-key org-mode-map [menu-bar hide] 'undefined)
  4733. (define-key org-mode-map [menu-bar show] 'undefined))
  4734. (org-load-modules-maybe)
  4735. (when (featurep 'xemacs)
  4736. (easy-menu-add org-org-menu)
  4737. (easy-menu-add org-tbl-menu))
  4738. (org-install-agenda-files-menu)
  4739. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4740. (add-to-invisibility-spec '(org-cwidth))
  4741. (add-to-invisibility-spec '(org-hide-block . t))
  4742. (when (featurep 'xemacs)
  4743. (setq-local line-move-ignore-invisible t))
  4744. (setq-local outline-regexp org-outline-regexp)
  4745. (setq-local outline-level 'org-outline-level)
  4746. (setq bidi-paragraph-direction 'left-to-right)
  4747. (when (and org-ellipsis
  4748. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4749. (fboundp 'make-glyph-code))
  4750. (unless org-display-table
  4751. (setq org-display-table (make-display-table)))
  4752. (set-display-table-slot
  4753. org-display-table 4
  4754. (vconcat (mapcar
  4755. (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
  4756. org-ellipsis)))
  4757. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4758. (setq buffer-display-table org-display-table))
  4759. (org-set-regexps-and-options)
  4760. (org-set-font-lock-defaults)
  4761. (when (and org-tag-faces (not org-tags-special-faces-re))
  4762. ;; tag faces set outside customize.... force initialization.
  4763. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4764. ;; Calc embedded
  4765. (setq-local calc-embedded-open-mode "# ")
  4766. ;; Modify a few syntax entries
  4767. (modify-syntax-entry ?@ "w")
  4768. (modify-syntax-entry ?\" "\"")
  4769. (modify-syntax-entry ?\\ "_")
  4770. (modify-syntax-entry ?~ "_")
  4771. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4772. ;; Activate before-change-function
  4773. (setq-local org-table-may-need-update t)
  4774. (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4775. ;; Check for running clock before killing a buffer
  4776. (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4777. ;; Initialize macros templates.
  4778. (org-macro-initialize-templates)
  4779. ;; Initialize radio targets.
  4780. (org-update-radio-target-regexp)
  4781. ;; Indentation.
  4782. (setq-local indent-line-function 'org-indent-line)
  4783. (setq-local indent-region-function 'org-indent-region)
  4784. ;; Filling and auto-filling.
  4785. (org-setup-filling)
  4786. ;; Comments.
  4787. (org-setup-comments-handling)
  4788. ;; Initialize cache.
  4789. (org-element-cache-reset)
  4790. ;; Beginning/end of defun
  4791. (setq-local beginning-of-defun-function 'org-backward-element)
  4792. (setq-local end-of-defun-function
  4793. (lambda ()
  4794. (if (not (org-at-heading-p))
  4795. (org-forward-element)
  4796. (org-forward-element)
  4797. (forward-char -1))))
  4798. ;; Next error for sparse trees
  4799. (setq-local next-error-function 'org-occur-next-match)
  4800. ;; Make sure dependence stuff works reliably, even for users who set it
  4801. ;; too late :-(
  4802. (if org-enforce-todo-dependencies
  4803. (add-hook 'org-blocker-hook
  4804. 'org-block-todo-from-children-or-siblings-or-parent)
  4805. (remove-hook 'org-blocker-hook
  4806. 'org-block-todo-from-children-or-siblings-or-parent))
  4807. (if org-enforce-todo-checkbox-dependencies
  4808. (add-hook 'org-blocker-hook
  4809. 'org-block-todo-from-checkboxes)
  4810. (remove-hook 'org-blocker-hook
  4811. 'org-block-todo-from-checkboxes))
  4812. ;; Align options lines
  4813. (setq-local
  4814. align-mode-rules-list
  4815. '((org-in-buffer-settings
  4816. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4817. (modes . '(org-mode)))))
  4818. ;; Imenu
  4819. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4820. ;; Make isearch reveal context
  4821. (if (or (featurep 'xemacs)
  4822. (not (boundp 'outline-isearch-open-invisible-function)))
  4823. ;; Emacs 21 and XEmacs make use of the hook
  4824. (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
  4825. ;; Emacs 22 deals with this through a special variable
  4826. (setq-local outline-isearch-open-invisible-function
  4827. (lambda (&rest _) (org-show-context 'isearch))))
  4828. ;; Setup the pcomplete hooks
  4829. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4830. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4831. (setq-local pcomplete-default-completion-function 'ignore)
  4832. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4833. (setq-local pcomplete-termination-string "")
  4834. (setq-local buffer-face-mode-face 'org-default)
  4835. ;; If empty file that did not turn on Org mode automatically, make
  4836. ;; it to.
  4837. (when (and org-insert-mode-line-in-empty-file
  4838. (org-called-interactively-p 'any)
  4839. (= (point-min) (point-max)))
  4840. (insert "# -*- mode: org -*-\n\n"))
  4841. (unless org-inhibit-startup
  4842. (org-unmodified
  4843. (when org-startup-with-beamer-mode (org-beamer-mode))
  4844. (when org-startup-align-all-tables
  4845. (org-table-map-tables #'org-table-align t))
  4846. (when org-startup-with-inline-images (org-display-inline-images))
  4847. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4848. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4849. (when org-startup-truncated (setq truncate-lines t))
  4850. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4851. (org-refresh-effort-properties)))
  4852. ;; Try to set `org-hide' face correctly.
  4853. (let ((foreground (org-find-invisible-foreground)))
  4854. (when foreground
  4855. (set-face-foreground 'org-hide foreground))))
  4856. ;; Update `customize-package-emacs-version-alist'
  4857. (add-to-list 'customize-package-emacs-version-alist
  4858. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4859. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4860. ("8.2.6" . "24.4") ("8.3" . "25.1")))
  4861. (defvar org-mode-transpose-word-syntax-table
  4862. (let ((st (make-syntax-table text-mode-syntax-table)))
  4863. (mapc (lambda(c) (modify-syntax-entry
  4864. (string-to-char (car c)) "w p" st))
  4865. org-emphasis-alist)
  4866. st))
  4867. (when (fboundp 'abbrev-table-put)
  4868. (abbrev-table-put org-mode-abbrev-table
  4869. :parents (list text-mode-abbrev-table)))
  4870. (defun org-find-invisible-foreground ()
  4871. (let ((candidates (remove
  4872. "unspecified-bg"
  4873. (nconc
  4874. (list (face-background 'default)
  4875. (face-background 'org-default))
  4876. (mapcar
  4877. (lambda (alist)
  4878. (when (boundp alist)
  4879. (cdr (assoc 'background-color (symbol-value alist)))))
  4880. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4881. (list (face-foreground 'org-hide))))))
  4882. (car (remove nil candidates))))
  4883. (defun org-current-time (&optional rounding-minutes past)
  4884. "Current time, possibly rounded to ROUNDING-MINUTES.
  4885. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4886. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4887. the rounding returns a past time."
  4888. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4889. (car org-time-stamp-rounding-minutes)))
  4890. (time (decode-time)) res)
  4891. (if (< r 1)
  4892. (current-time)
  4893. (setq res
  4894. (apply 'encode-time
  4895. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4896. (nthcdr 2 time))))
  4897. (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
  4898. (seconds-to-time (- (org-float-time res) (* r 60)))
  4899. res))))
  4900. (defun org-today ()
  4901. "Return today date, considering `org-extend-today-until'."
  4902. (time-to-days
  4903. (time-subtract (current-time)
  4904. (list 0 (* 3600 org-extend-today-until) 0))))
  4905. ;;;; Font-Lock stuff, including the activators
  4906. (defvar org-mouse-map (make-sparse-keymap))
  4907. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4908. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4909. (when org-mouse-1-follows-link
  4910. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4911. (when org-tab-follows-link
  4912. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4913. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4914. (require 'font-lock)
  4915. (defconst org-non-link-chars "]\t\n\r<>")
  4916. (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
  4917. "file+sys" "news" "shell" "elisp" "doi" "message"
  4918. "help"))
  4919. (defvar org-link-types-re nil
  4920. "Matches a link that has a url-like prefix like \"http:\"")
  4921. (defvar org-link-re-with-space nil
  4922. "Matches a link with spaces, optional angular brackets around it.")
  4923. (defvar org-link-re-with-space2 nil
  4924. "Matches a link with spaces, optional angular brackets around it.")
  4925. (defvar org-link-re-with-space3 nil
  4926. "Matches a link with spaces, only for internal part in bracket links.")
  4927. (defvar org-angle-link-re nil
  4928. "Matches link with angular brackets, spaces are allowed.")
  4929. (defvar org-plain-link-re nil
  4930. "Matches plain link, without spaces.")
  4931. (defvar org-bracket-link-regexp nil
  4932. "Matches a link in double brackets.")
  4933. (defvar org-bracket-link-analytic-regexp nil
  4934. "Regular expression used to analyze links.
  4935. Here is what the match groups contain after a match:
  4936. 1: http:
  4937. 2: http
  4938. 3: path
  4939. 4: [desc]
  4940. 5: desc")
  4941. (defvar org-bracket-link-analytic-regexp++ nil
  4942. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4943. (defvar org-any-link-re nil
  4944. "Regular expression matching any link.")
  4945. (defconst org-match-sexp-depth 3
  4946. "Number of stacked braces for sub/superscript matching.")
  4947. (defun org-create-multibrace-regexp (left right n)
  4948. "Create a regular expression which will match a balanced sexp.
  4949. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4950. as single character strings.
  4951. The regexp returned will match the entire expression including the
  4952. delimiters. It will also define a single group which contains the
  4953. match except for the outermost delimiters. The maximum depth of
  4954. stacked delimiters is N. Escaping delimiters is not possible."
  4955. (let* ((nothing (concat "[^" left right "]*?"))
  4956. (or "\\|")
  4957. (re nothing)
  4958. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4959. (while (> n 1)
  4960. (setq n (1- n)
  4961. re (concat re or next)
  4962. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4963. (concat left "\\(" re "\\)" right)))
  4964. (defconst org-match-substring-regexp
  4965. (concat
  4966. "\\(\\S-\\)\\([_^]\\)\\("
  4967. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4968. "\\|"
  4969. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4970. "\\|"
  4971. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4972. "The regular expression matching a sub- or superscript.")
  4973. (defconst org-match-substring-with-braces-regexp
  4974. (concat
  4975. "\\(\\S-\\)\\([_^]\\)"
  4976. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4977. "The regular expression matching a sub- or superscript, forcing braces.")
  4978. (defun org-make-link-regexps ()
  4979. "Update the link regular expressions.
  4980. This should be called after the variable `org-link-types' has changed."
  4981. (let ((types-re (regexp-opt org-link-types t)))
  4982. (setq org-link-types-re
  4983. (concat "\\`" types-re ":")
  4984. org-link-re-with-space
  4985. (concat "<?" types-re ":"
  4986. "\\([^" org-non-link-chars " ]"
  4987. "[^" org-non-link-chars "]*"
  4988. "[^" org-non-link-chars " ]\\)>?")
  4989. org-link-re-with-space2
  4990. (concat "<?" types-re ":"
  4991. "\\([^" org-non-link-chars " ]"
  4992. "[^\t\n\r]*"
  4993. "[^" org-non-link-chars " ]\\)>?")
  4994. org-link-re-with-space3
  4995. (concat "<?" types-re ":"
  4996. "\\([^" org-non-link-chars " ]"
  4997. "[^\t\n\r]*\\)")
  4998. org-angle-link-re
  4999. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5000. types-re)
  5001. org-plain-link-re
  5002. (concat
  5003. "\\<" types-re ":"
  5004. (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
  5005. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5006. org-bracket-link-regexp
  5007. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5008. org-bracket-link-analytic-regexp
  5009. (concat
  5010. "\\[\\["
  5011. "\\(" types-re ":\\)?"
  5012. "\\([^]]+\\)"
  5013. "\\]"
  5014. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5015. "\\]")
  5016. org-bracket-link-analytic-regexp++
  5017. (concat
  5018. "\\[\\["
  5019. "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
  5020. "\\([^]]+\\)"
  5021. "\\]"
  5022. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5023. "\\]")
  5024. org-any-link-re
  5025. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5026. org-angle-link-re "\\)\\|\\("
  5027. org-plain-link-re "\\)"))))
  5028. (org-make-link-regexps)
  5029. (defvar org-emph-face nil)
  5030. (defun org-do-emphasis-faces (limit)
  5031. "Run through the buffer and emphasize strings."
  5032. (let (rtn a)
  5033. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5034. (let* ((border (char-after (match-beginning 3)))
  5035. (bre (regexp-quote (char-to-string border))))
  5036. (when (and (not (= border (char-after (match-beginning 4))))
  5037. (not (string-match-p (concat bre ".*" bre)
  5038. (replace-regexp-in-string
  5039. "\n" " "
  5040. (substring (match-string 2) 1 -1)))))
  5041. (setq rtn t)
  5042. (setq a (assoc (match-string 3) org-emphasis-alist))
  5043. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5044. 'face
  5045. (nth 1 a))
  5046. (and (nth 2 a)
  5047. (org-remove-flyspell-overlays-in
  5048. (match-beginning 0) (match-end 0)))
  5049. (add-text-properties (match-beginning 2) (match-end 2)
  5050. '(font-lock-multiline t org-emphasis t))
  5051. (when org-hide-emphasis-markers
  5052. (add-text-properties (match-end 4) (match-beginning 5)
  5053. '(invisible org-link))
  5054. (add-text-properties (match-beginning 3) (match-end 3)
  5055. '(invisible org-link)))))
  5056. (goto-char (1+ (match-beginning 0))))
  5057. rtn))
  5058. (defun org-emphasize (&optional char)
  5059. "Insert or change an emphasis, i.e. a font like bold or italic.
  5060. If there is an active region, change that region to a new emphasis.
  5061. If there is no region, just insert the marker characters and position
  5062. the cursor between them.
  5063. CHAR should be the marker character. If it is a space, it means to
  5064. remove the emphasis of the selected region.
  5065. If CHAR is not given (for example in an interactive call) it will be
  5066. prompted for."
  5067. (interactive)
  5068. (let ((erc org-emphasis-regexp-components)
  5069. (string "") beg end move s)
  5070. (if (org-region-active-p)
  5071. (setq beg (region-beginning)
  5072. end (region-end)
  5073. string (buffer-substring beg end))
  5074. (setq move t))
  5075. (unless char
  5076. (message "Emphasis marker or tag: [%s]"
  5077. (mapconcat #'car org-emphasis-alist ""))
  5078. (setq char (read-char-exclusive)))
  5079. (if (equal char ?\s)
  5080. (setq s ""
  5081. move nil)
  5082. (unless (assoc (char-to-string char) org-emphasis-alist)
  5083. (user-error "No such emphasis marker: \"%c\"" char))
  5084. (setq s (char-to-string char)))
  5085. (while (and (> (length string) 1)
  5086. (equal (substring string 0 1) (substring string -1))
  5087. (assoc (substring string 0 1) org-emphasis-alist))
  5088. (setq string (substring string 1 -1)))
  5089. (setq string (concat s string s))
  5090. (when beg (delete-region beg end))
  5091. (unless (or (bolp)
  5092. (string-match (concat "[" (nth 0 erc) "\n]")
  5093. (char-to-string (char-before (point)))))
  5094. (insert " "))
  5095. (unless (or (eobp)
  5096. (string-match (concat "[" (nth 1 erc) "\n]")
  5097. (char-to-string (char-after (point)))))
  5098. (insert " ") (backward-char 1))
  5099. (insert string)
  5100. (and move (backward-char 1))))
  5101. (defconst org-nonsticky-props
  5102. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5103. (defsubst org-rear-nonsticky-at (pos)
  5104. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5105. (defun org-activate-plain-links (limit)
  5106. "Add link properties for plain links."
  5107. (let (f hl)
  5108. (when (and (re-search-forward (concat org-plain-link-re) limit t)
  5109. (not (member 'org-tag
  5110. (get-text-property (1- (match-beginning 0)) 'face)))
  5111. (not (org-in-src-block-p)))
  5112. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5113. (setq f (get-text-property (match-beginning 0) 'face))
  5114. (setq hl (org-match-string-no-properties 0))
  5115. (unless (or (eq f 'org-tag)
  5116. (and (listp f) (memq 'org-tag f)))
  5117. (add-text-properties (match-beginning 0) (match-end 0)
  5118. (list 'mouse-face 'highlight
  5119. 'face 'org-link
  5120. 'htmlize-link `(:uri ,hl)
  5121. 'keymap org-mouse-map))
  5122. (org-rear-nonsticky-at (match-end 0)))
  5123. t)))
  5124. (defun org-activate-code (limit)
  5125. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5126. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5127. (remove-text-properties (match-beginning 0) (match-end 0)
  5128. '(display t invisible t intangible t))
  5129. t))
  5130. (defcustom org-src-fontify-natively t
  5131. "When non-nil, fontify code in code blocks."
  5132. :type 'boolean
  5133. :version "24.4"
  5134. :package-version '(Org . "8.3")
  5135. :group 'org-appearance
  5136. :group 'org-babel)
  5137. (defcustom org-allow-promoting-top-level-subtree nil
  5138. "When non-nil, allow promoting a top level subtree.
  5139. The leading star of the top level headline will be replaced
  5140. by a #."
  5141. :type 'boolean
  5142. :version "24.1"
  5143. :group 'org-appearance)
  5144. (defun org-fontify-meta-lines-and-blocks (limit)
  5145. (condition-case nil
  5146. (org-fontify-meta-lines-and-blocks-1 limit)
  5147. (error (message "org-mode fontification error"))))
  5148. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5149. "Fontify #+ lines and blocks."
  5150. (let ((case-fold-search t))
  5151. (when (re-search-forward
  5152. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5153. limit t)
  5154. (let ((beg (match-beginning 0))
  5155. (block-start (match-end 0))
  5156. (block-end nil)
  5157. (lang (match-string 7))
  5158. (beg1 (line-beginning-position 2))
  5159. (dc1 (downcase (match-string 2)))
  5160. (dc3 (downcase (match-string 3)))
  5161. end end1 quoting block-type)
  5162. (cond
  5163. ((and (match-end 4) (equal dc3 "+begin"))
  5164. ;; Truly a block
  5165. (setq block-type (downcase (match-string 5))
  5166. quoting (member block-type org-protecting-blocks))
  5167. (when (re-search-forward
  5168. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5169. nil t) ;; on purpose, we look further than LIMIT
  5170. (setq end (min (point-max) (match-end 0))
  5171. end1 (min (point-max) (1- (match-beginning 0))))
  5172. (setq block-end (match-beginning 0))
  5173. (when quoting
  5174. (org-remove-flyspell-overlays-in beg1 end1)
  5175. (remove-text-properties beg end
  5176. '(display t invisible t intangible t)))
  5177. (add-text-properties
  5178. beg end '(font-lock-fontified t font-lock-multiline t))
  5179. (add-text-properties beg beg1 '(face org-meta-line))
  5180. (org-remove-flyspell-overlays-in beg beg1)
  5181. (add-text-properties ; For end_src
  5182. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5183. (org-remove-flyspell-overlays-in end1 end)
  5184. (cond
  5185. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5186. (org-src-font-lock-fontify-block lang block-start block-end)
  5187. (add-text-properties beg1 block-end '(src-block t)))
  5188. (quoting
  5189. (add-text-properties beg1 (min (point-max) (1+ end1))
  5190. '(face org-block))) ; end of source block
  5191. ((not org-fontify-quote-and-verse-blocks))
  5192. ((string= block-type "quote")
  5193. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5194. ((string= block-type "verse")
  5195. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5196. (add-text-properties beg beg1 '(face org-block-begin-line))
  5197. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5198. '(face org-block-end-line))
  5199. t))
  5200. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5201. (org-remove-flyspell-overlays-in
  5202. (match-beginning 0)
  5203. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5204. (add-text-properties
  5205. beg (match-end 3)
  5206. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5207. '(font-lock-fontified t invisible t)
  5208. '(font-lock-fontified t face org-document-info-keyword)))
  5209. (add-text-properties
  5210. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5211. (if (string-equal dc1 "+title:")
  5212. '(font-lock-fontified t face org-document-title)
  5213. '(font-lock-fontified t face org-document-info))))
  5214. ((equal dc1 "+caption:")
  5215. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5216. (remove-text-properties (match-beginning 0) (match-end 0)
  5217. '(display t invisible t intangible t))
  5218. (add-text-properties (match-beginning 1) (match-end 3)
  5219. '(font-lock-fontified t face org-meta-line))
  5220. (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
  5221. '(font-lock-fontified t face org-block))
  5222. t)
  5223. ((member dc3 '(" " ""))
  5224. (org-remove-flyspell-overlays-in beg (match-end 0))
  5225. (add-text-properties
  5226. beg (match-end 0)
  5227. '(font-lock-fontified t face font-lock-comment-face)))
  5228. (t ;; just any other in-buffer setting, but not indented
  5229. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5230. (remove-text-properties (match-beginning 0) (match-end 0)
  5231. '(display t invisible t intangible t))
  5232. (add-text-properties beg (match-end 0)
  5233. '(font-lock-fontified t face org-meta-line))
  5234. t))))))
  5235. (defun org-fontify-drawers (limit)
  5236. "Fontify drawers."
  5237. (when (re-search-forward org-drawer-regexp limit t)
  5238. (add-text-properties
  5239. (match-beginning 0) (match-end 0)
  5240. '(font-lock-fontified t face org-special-keyword))
  5241. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5242. t))
  5243. (defun org-fontify-macros (limit)
  5244. "Fontify macros."
  5245. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5246. (add-text-properties
  5247. (match-beginning 0) (match-end 0)
  5248. '(font-lock-fontified t face org-macro))
  5249. (when org-hide-macro-markers
  5250. (add-text-properties (match-end 2) (match-beginning 2)
  5251. '(invisible t))
  5252. (add-text-properties (match-beginning 1) (match-end 1)
  5253. '(invisible t)))
  5254. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5255. t))
  5256. (defun org-activate-angle-links (limit)
  5257. "Add text properties for angle links."
  5258. (when (and (re-search-forward org-angle-link-re limit t)
  5259. (not (org-in-src-block-p)))
  5260. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5261. (add-text-properties (match-beginning 0) (match-end 0)
  5262. (list 'mouse-face 'highlight
  5263. 'keymap org-mouse-map
  5264. 'font-lock-multiline t))
  5265. (org-rear-nonsticky-at (match-end 0))
  5266. t))
  5267. (defun org-activate-footnote-links (limit)
  5268. "Add text properties for footnotes."
  5269. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5270. (when fn
  5271. (let* ((beg (nth 1 fn))
  5272. (end (nth 2 fn))
  5273. (label (car fn))
  5274. (referencep (/= (line-beginning-position) beg)))
  5275. (when (and referencep (nth 3 fn))
  5276. (save-excursion
  5277. (goto-char beg)
  5278. (search-forward (or label "fn:"))
  5279. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5280. (add-text-properties beg end
  5281. (list 'mouse-face 'highlight
  5282. 'keymap org-mouse-map
  5283. 'help-echo
  5284. (if referencep "Footnote reference"
  5285. "Footnote definition")
  5286. 'font-lock-fontified t
  5287. 'font-lock-multiline t
  5288. 'face 'org-footnote))))))
  5289. (defun org-activate-bracket-links (limit)
  5290. "Add text properties for bracketed links."
  5291. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5292. (not (org-in-src-block-p)))
  5293. (let* ((hl (org-match-string-no-properties 1))
  5294. (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
  5295. (ip (org-maybe-intangible
  5296. (list 'invisible 'org-link
  5297. 'keymap org-mouse-map 'mouse-face 'highlight
  5298. 'font-lock-multiline t 'help-echo help
  5299. 'htmlize-link `(:uri ,hl))))
  5300. (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
  5301. 'font-lock-multiline t 'help-echo help
  5302. 'htmlize-link `(:uri ,hl))))
  5303. ;; We need to remove the invisible property here. Table narrowing
  5304. ;; may have made some of this invisible.
  5305. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5306. (remove-text-properties (match-beginning 0) (match-end 0)
  5307. '(invisible nil))
  5308. (if (match-end 3)
  5309. (progn
  5310. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5311. (org-rear-nonsticky-at (match-beginning 3))
  5312. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5313. (org-rear-nonsticky-at (match-end 3))
  5314. (add-text-properties (match-end 3) (match-end 0) ip)
  5315. (org-rear-nonsticky-at (match-end 0)))
  5316. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5317. (org-rear-nonsticky-at (match-beginning 1))
  5318. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5319. (org-rear-nonsticky-at (match-end 1))
  5320. (add-text-properties (match-end 1) (match-end 0) ip)
  5321. (org-rear-nonsticky-at (match-end 0)))
  5322. t)))
  5323. (defun org-activate-dates (limit)
  5324. "Add text properties for dates."
  5325. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5326. (not (equal (char-before (match-beginning 0)) 91)))
  5327. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5328. (add-text-properties (match-beginning 0) (match-end 0)
  5329. (list 'mouse-face 'highlight
  5330. 'keymap org-mouse-map))
  5331. (org-rear-nonsticky-at (match-end 0))
  5332. (when org-display-custom-times
  5333. (if (match-end 3)
  5334. (org-display-custom-time (match-beginning 3) (match-end 3))
  5335. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5336. t))
  5337. (defvar-local org-target-link-regexp nil
  5338. "Regular expression matching radio targets in plain text.")
  5339. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5340. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5341. border border border))
  5342. "Regular expression matching a link target.")
  5343. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5344. "Regular expression matching a radio target.")
  5345. (defconst org-any-target-regexp
  5346. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5347. "Regular expression matching any target.")
  5348. (defun org-activate-target-links (limit)
  5349. "Add text properties for target matches."
  5350. (when org-target-link-regexp
  5351. (let ((case-fold-search t))
  5352. (when (re-search-forward org-target-link-regexp limit t)
  5353. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5354. (add-text-properties (match-beginning 1) (match-end 1)
  5355. (list 'mouse-face 'highlight
  5356. 'keymap org-mouse-map
  5357. 'help-echo "Radio target link"
  5358. 'org-linked-text t))
  5359. (org-rear-nonsticky-at (match-end 1))
  5360. t))))
  5361. (defun org-update-radio-target-regexp ()
  5362. "Find all radio targets in this file and update the regular expression.
  5363. Also refresh fontification if needed."
  5364. (interactive)
  5365. (let ((old-regexp org-target-link-regexp)
  5366. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5367. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5368. (targets
  5369. (org-with-wide-buffer
  5370. (goto-char (point-min))
  5371. (let (rtn)
  5372. (while (re-search-forward org-radio-target-regexp nil t)
  5373. ;; Make sure point is really within the object.
  5374. (backward-char)
  5375. (let ((obj (org-element-context)))
  5376. (when (eq (org-element-type obj) 'radio-target)
  5377. (cl-pushnew (org-element-property :value obj) rtn
  5378. :test #'equal))))
  5379. rtn))))
  5380. (setq org-target-link-regexp
  5381. (and targets
  5382. (concat before-re
  5383. (mapconcat
  5384. (lambda (x)
  5385. (replace-regexp-in-string
  5386. " +" "\\s-+" (regexp-quote x) t t))
  5387. targets
  5388. "\\|")
  5389. after-re)))
  5390. (unless (equal old-regexp org-target-link-regexp)
  5391. ;; Clean-up cache.
  5392. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5393. ((not org-target-link-regexp) old-regexp)
  5394. (t
  5395. (concat before-re
  5396. (mapconcat
  5397. (lambda (re)
  5398. (substring re (length before-re)
  5399. (- (length after-re))))
  5400. (list old-regexp org-target-link-regexp)
  5401. "\\|")
  5402. after-re)))))
  5403. (org-with-wide-buffer
  5404. (goto-char (point-min))
  5405. (while (re-search-forward regexp nil t)
  5406. (org-element-cache-refresh (match-beginning 1)))))
  5407. ;; Re fontify buffer.
  5408. (when (memq 'radio org-highlight-links)
  5409. (org-restart-font-lock)))))
  5410. (defun org-hide-wide-columns (limit)
  5411. (let (s e)
  5412. (setq s (text-property-any (point) (or limit (point-max))
  5413. 'org-cwidth t))
  5414. (when s
  5415. (setq e (next-single-property-change s 'org-cwidth))
  5416. (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
  5417. (goto-char e)
  5418. t)))
  5419. (defvar org-latex-and-related-regexp nil
  5420. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5421. (defun org-compute-latex-and-related-regexp ()
  5422. "Compute regular expression for LaTeX, entities and sub/superscript.
  5423. Result depends on variable `org-highlight-latex-and-related'."
  5424. (setq-local
  5425. org-latex-and-related-regexp
  5426. (let* ((re-sub
  5427. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5428. ((eq org-use-sub-superscripts '{})
  5429. (list org-match-substring-with-braces-regexp))
  5430. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5431. (re-latex
  5432. (when (memq 'latex org-highlight-latex-and-related)
  5433. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5434. (delq nil
  5435. (mapcar (lambda (x)
  5436. (and (member (car x) matchers) (nth 1 x)))
  5437. org-latex-regexps)))))
  5438. (re-entities
  5439. (when (memq 'entities org-highlight-latex-and-related)
  5440. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5441. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5442. (defun org-do-latex-and-related (limit)
  5443. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5444. LIMIT bounds the search for syntax to highlight. Stop at first
  5445. highlighted object, if any. Return t if some highlighting was
  5446. done, nil otherwise."
  5447. (when (org-string-nw-p org-latex-and-related-regexp)
  5448. (catch 'found
  5449. (while (re-search-forward org-latex-and-related-regexp limit t)
  5450. (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
  5451. 'face))
  5452. '(org-code org-verbatim underline))
  5453. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5454. '(?_ ?^))
  5455. 1
  5456. 0)))
  5457. (font-lock-prepend-text-property
  5458. (+ offset (match-beginning 0)) (match-end 0)
  5459. 'face 'org-latex-and-related)
  5460. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5461. '(font-lock-multiline t)))
  5462. (throw 'found t)))
  5463. nil)))
  5464. (defun org-restart-font-lock ()
  5465. "Restart `font-lock-mode', to force refontification."
  5466. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5467. (font-lock-mode -1)
  5468. (font-lock-mode 1)))
  5469. (defun org-activate-tags (limit)
  5470. (when (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
  5471. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5472. (add-text-properties (match-beginning 1) (match-end 1)
  5473. (list 'mouse-face 'highlight
  5474. 'keymap org-mouse-map))
  5475. (org-rear-nonsticky-at (match-end 1))
  5476. t))
  5477. (defun org-outline-level ()
  5478. "Compute the outline level of the heading at point.
  5479. If this is called at a normal headline, the level is the number
  5480. of stars. Use `org-reduced-level' to remove the effect of
  5481. `org-odd-levels'. Unlike to `org-current-level', this function
  5482. takes into consideration inlinetasks."
  5483. (org-with-wide-buffer
  5484. (end-of-line)
  5485. (if (re-search-backward org-outline-regexp-bol nil t)
  5486. (1- (- (match-end 0) (match-beginning 0)))
  5487. 0)))
  5488. (defvar org-font-lock-keywords nil)
  5489. (defsubst org-re-property (property &optional literal allow-null value)
  5490. "Return a regexp matching a PROPERTY line.
  5491. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5492. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5493. non-nil, match properties even without a value.
  5494. Match group 3 is set to the value when it exists. If there is no
  5495. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5496. With optional argument VALUE, match only property lines with
  5497. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5498. unless LITERAL is non-nil."
  5499. (concat
  5500. "^\\(?4:[ \t]*\\)"
  5501. (format "\\(?1::\\(?2:%s\\):\\)"
  5502. (if literal property (regexp-quote property)))
  5503. (cond (value
  5504. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5505. (if literal value (regexp-quote value))))
  5506. (allow-null
  5507. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5508. (t
  5509. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5510. (defconst org-property-re
  5511. (org-re-property "\\S-+" 'literal t)
  5512. "Regular expression matching a property line.
  5513. There are four matching groups:
  5514. 1: :PROPKEY: including the leading and trailing colon,
  5515. 2: PROPKEY without the leading and trailing colon,
  5516. 3: PROPVAL without leading or trailing spaces,
  5517. 4: the indentation of the current line,
  5518. 5: trailing whitespace.")
  5519. (defvar org-font-lock-hook nil
  5520. "Functions to be called for special font lock stuff.")
  5521. (defvar org-font-lock-set-keywords-hook nil
  5522. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5523. This is called after `org-font-lock-extra-keywords' is defined, but before
  5524. it is installed to be used by font lock. This can be useful if something
  5525. needs to be inserted at a specific position in the font-lock sequence.")
  5526. (defun org-font-lock-hook (limit)
  5527. "Run `org-font-lock-hook' within LIMIT."
  5528. (run-hook-with-args 'org-font-lock-hook limit))
  5529. (defun org-set-font-lock-defaults ()
  5530. "Set font lock defaults for the current buffer."
  5531. (let* ((em org-fontify-emphasized-text)
  5532. (lk org-highlight-links)
  5533. (org-font-lock-extra-keywords
  5534. (list
  5535. ;; Call the hook
  5536. '(org-font-lock-hook)
  5537. ;; Headlines
  5538. `(,(if org-fontify-whole-heading-line
  5539. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5540. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5541. (1 (org-get-level-face 1))
  5542. (2 (org-get-level-face 2))
  5543. (3 (org-get-level-face 3)))
  5544. ;; Table lines
  5545. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5546. (1 'org-table t))
  5547. ;; Table internals
  5548. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5549. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5550. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5551. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5552. ;; Drawers
  5553. '(org-fontify-drawers)
  5554. ;; Properties
  5555. (list org-property-re
  5556. '(1 'org-special-keyword t)
  5557. '(3 'org-property-value t))
  5558. ;; Links
  5559. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5560. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5561. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
  5562. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
  5563. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5564. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5565. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5566. ;; Targets.
  5567. (list org-any-target-regexp '(0 'org-target t))
  5568. ;; Diary sexps.
  5569. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5570. ;; Macro
  5571. '(org-fontify-macros)
  5572. '(org-hide-wide-columns (0 nil append))
  5573. ;; TODO keyword
  5574. (list (format org-heading-keyword-regexp-format
  5575. org-todo-regexp)
  5576. '(2 (org-get-todo-face 2) t))
  5577. ;; DONE
  5578. (if org-fontify-done-headline
  5579. (list (format org-heading-keyword-regexp-format
  5580. (concat
  5581. "\\(?:"
  5582. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5583. "\\)"))
  5584. '(2 'org-headline-done t))
  5585. nil)
  5586. ;; Priorities
  5587. '(org-font-lock-add-priority-faces)
  5588. ;; Tags
  5589. '(org-font-lock-add-tag-faces)
  5590. ;; Tags groups
  5591. (when (and org-group-tags org-tag-groups-alist)
  5592. (list (concat org-outline-regexp-bol ".+\\(:"
  5593. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5594. ":\\).*$")
  5595. '(1 'org-tag-group prepend)))
  5596. ;; Special keywords
  5597. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5598. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5599. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5600. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5601. ;; Emphasis
  5602. (when em
  5603. (if (featurep 'xemacs)
  5604. '(org-do-emphasis-faces (0 nil append))
  5605. '(org-do-emphasis-faces)))
  5606. ;; Checkboxes
  5607. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5608. 1 'org-checkbox prepend)
  5609. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5610. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5611. (0 (org-get-checkbox-statistics-face) t)))
  5612. ;; Description list items
  5613. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5614. 1 'org-list-dt prepend)
  5615. ;; ARCHIVEd headings
  5616. (list (concat
  5617. org-outline-regexp-bol
  5618. "\\(.*:" org-archive-tag ":.*\\)")
  5619. '(1 'org-archived prepend))
  5620. ;; Specials
  5621. '(org-do-latex-and-related)
  5622. '(org-fontify-entities)
  5623. '(org-raise-scripts)
  5624. ;; Code
  5625. '(org-activate-code (1 'org-code t))
  5626. ;; COMMENT
  5627. (list (format
  5628. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5629. org-todo-regexp
  5630. org-comment-string)
  5631. '(9 'org-special-keyword t))
  5632. ;; Blocks and meta lines
  5633. '(org-fontify-meta-lines-and-blocks))))
  5634. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5635. (run-hooks 'org-font-lock-set-keywords-hook)
  5636. ;; Now set the full font-lock-keywords
  5637. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5638. (setq-local font-lock-defaults
  5639. '(org-font-lock-keywords t nil nil backward-paragraph))
  5640. (kill-local-variable 'font-lock-keywords) nil))
  5641. (defun org-toggle-pretty-entities ()
  5642. "Toggle the composition display of entities as UTF8 characters."
  5643. (interactive)
  5644. (setq-local org-pretty-entities (not org-pretty-entities))
  5645. (org-restart-font-lock)
  5646. (if org-pretty-entities
  5647. (message "Entities are now displayed as UTF8 characters")
  5648. (save-restriction
  5649. (widen)
  5650. (org-decompose-region (point-min) (point-max))
  5651. (message "Entities are now displayed as plain text"))))
  5652. (defvar-local org-custom-properties-overlays nil
  5653. "List of overlays used for custom properties.")
  5654. (defun org-toggle-custom-properties-visibility ()
  5655. "Display or hide properties in `org-custom-properties'."
  5656. (interactive)
  5657. (if org-custom-properties-overlays
  5658. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5659. (setq org-custom-properties-overlays nil))
  5660. (when org-custom-properties
  5661. (org-with-wide-buffer
  5662. (goto-char (point-min))
  5663. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5664. (while (re-search-forward regexp nil t)
  5665. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5666. (when (and end (< (point) end))
  5667. ;; Hide first custom property in current drawer.
  5668. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5669. (overlay-put o 'invisible t)
  5670. (overlay-put o 'org-custom-property t)
  5671. (push o org-custom-properties-overlays))
  5672. ;; Hide additional custom properties in the same drawer.
  5673. (while (re-search-forward regexp end t)
  5674. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5675. (overlay-put o 'invisible t)
  5676. (overlay-put o 'org-custom-property t)
  5677. (push o org-custom-properties-overlays)))))
  5678. ;; Each entry is limited to a single property drawer.
  5679. (outline-next-heading)))))))
  5680. (defun org-fontify-entities (limit)
  5681. "Find an entity to fontify."
  5682. (let (ee)
  5683. (when org-pretty-entities
  5684. (catch 'match
  5685. ;; "\_ "-family is left out on purpose. Only the first one,
  5686. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5687. ;; confusing when adding a second white space character.
  5688. (while (re-search-forward
  5689. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5690. limit t)
  5691. (when (and (not (org-at-comment-p))
  5692. (setq ee (org-entity-get (match-string 1)))
  5693. (= (length (nth 6 ee)) 1))
  5694. (let* ((end (if (equal (match-string 2) "{}")
  5695. (match-end 2)
  5696. (match-end 1))))
  5697. (add-text-properties
  5698. (match-beginning 0) end
  5699. (list 'font-lock-fontified t))
  5700. (compose-region (match-beginning 0) end
  5701. (nth 6 ee) nil)
  5702. (backward-char 1)
  5703. (throw 'match t))))
  5704. nil))))
  5705. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5706. "Fontify string S like in Org-mode."
  5707. (with-temp-buffer
  5708. (insert s)
  5709. (let ((org-odd-levels-only odd-levels))
  5710. (org-mode)
  5711. (font-lock-ensure)
  5712. (buffer-string))))
  5713. (defvar org-m nil)
  5714. (defvar org-l nil)
  5715. (defvar org-f nil)
  5716. (defun org-get-level-face (n)
  5717. "Get the right face for match N in font-lock matching of headlines."
  5718. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5719. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5720. (if org-cycle-level-faces
  5721. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5722. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5723. (cond
  5724. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5725. ((eq n 2) org-f)
  5726. (t (unless org-level-color-stars-only org-f))))
  5727. (defun org-face-from-face-or-color (context inherit face-or-color)
  5728. "Create a face list that inherits INHERIT, but sets the foreground color.
  5729. When FACE-OR-COLOR is not a string, just return it."
  5730. (if (stringp face-or-color)
  5731. (list :inherit inherit
  5732. (cdr (assoc context org-faces-easy-properties))
  5733. face-or-color)
  5734. face-or-color))
  5735. (defun org-get-todo-face (kwd)
  5736. "Get the right face for a TODO keyword KWD.
  5737. If KWD is a number, get the corresponding match group."
  5738. (when (numberp kwd) (setq kwd (match-string kwd)))
  5739. (or (org-face-from-face-or-color
  5740. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5741. (and (member kwd org-done-keywords) 'org-done)
  5742. 'org-todo))
  5743. (defun org-get-priority-face (priority)
  5744. "Get the right face for PRIORITY.
  5745. PRIORITY is a character."
  5746. (or (org-face-from-face-or-color
  5747. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5748. 'org-priority))
  5749. (defun org-get-tag-face (tag)
  5750. "Get the right face for TAG.
  5751. If TAG is a number, get the corresponding match group."
  5752. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5753. (or (org-face-from-face-or-color
  5754. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5755. 'org-tag)))
  5756. (defun org-font-lock-add-priority-faces (limit)
  5757. "Add the special priority faces."
  5758. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5759. (add-text-properties
  5760. (match-beginning 1) (match-end 1)
  5761. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5762. 'font-lock-fontified t))))
  5763. (defun org-font-lock-add-tag-faces (limit)
  5764. "Add the special tag faces."
  5765. (when (and org-tag-faces org-tags-special-faces-re)
  5766. (while (re-search-forward org-tags-special-faces-re limit t)
  5767. (add-text-properties (match-beginning 1) (match-end 1)
  5768. (list 'face (org-get-tag-face 1)
  5769. 'font-lock-fontified t))
  5770. (backward-char 1))))
  5771. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5772. "Remove fontification and activation overlays from links."
  5773. (font-lock-default-unfontify-region beg end)
  5774. (let* ((buffer-undo-list t)
  5775. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5776. (inhibit-modification-hooks t)
  5777. deactivate-mark buffer-file-name buffer-file-truename)
  5778. (org-decompose-region beg end)
  5779. (remove-text-properties beg end
  5780. '(mouse-face t keymap t org-linked-text t
  5781. invisible t intangible t
  5782. org-emphasis t))
  5783. (org-remove-font-lock-display-properties beg end)))
  5784. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5785. ((raise 0.3) (height 0.7))
  5786. ((raise -0.5))
  5787. ((raise 0.5)))
  5788. "Display properties for showing superscripts and subscripts.")
  5789. (defun org-remove-font-lock-display-properties (beg end)
  5790. "Remove specific display properties that have been added by font lock.
  5791. The will remove the raise properties that are used to show superscripts
  5792. and subscripts."
  5793. (let (next prop)
  5794. (while (< beg end)
  5795. (setq next (next-single-property-change beg 'display nil end)
  5796. prop (get-text-property beg 'display))
  5797. (when (member prop org-script-display)
  5798. (put-text-property beg next 'display nil))
  5799. (setq beg next))))
  5800. (defun org-raise-scripts (limit)
  5801. "Add raise properties to sub/superscripts."
  5802. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5803. (re-search-forward
  5804. (if (eq org-use-sub-superscripts t)
  5805. org-match-substring-regexp
  5806. org-match-substring-with-braces-regexp)
  5807. limit t))
  5808. (let* ((pos (point)) table-p comment-p
  5809. (mpos (match-beginning 3))
  5810. (emph-p (get-text-property mpos 'org-emphasis))
  5811. (link-p (get-text-property mpos 'mouse-face))
  5812. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5813. (goto-char (point-at-bol))
  5814. (setq table-p (org-looking-at-p org-table-dataline-regexp)
  5815. comment-p (org-looking-at-p "^[ \t]*#[ +]"))
  5816. (goto-char pos)
  5817. ;; Handle a_b^c
  5818. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5819. (unless (or comment-p emph-p link-p keyw-p)
  5820. (put-text-property (match-beginning 3) (match-end 0)
  5821. 'display
  5822. (if (equal (char-after (match-beginning 2)) ?^)
  5823. (nth (if table-p 3 1) org-script-display)
  5824. (nth (if table-p 2 0) org-script-display)))
  5825. (add-text-properties (match-beginning 2) (match-end 2)
  5826. (list 'invisible t
  5827. 'org-dwidth t 'org-dwidth-n 1))
  5828. (if (and (eq (char-after (match-beginning 3)) ?{)
  5829. (eq (char-before (match-end 3)) ?}))
  5830. (progn
  5831. (add-text-properties
  5832. (match-beginning 3) (1+ (match-beginning 3))
  5833. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5834. (add-text-properties
  5835. (1- (match-end 3)) (match-end 3)
  5836. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5837. t)))
  5838. ;;;; Visibility cycling, including org-goto and indirect buffer
  5839. ;;; Cycling
  5840. (defvar-local org-cycle-global-status nil)
  5841. (put 'org-cycle-global-status 'org-state t)
  5842. (defvar-local org-cycle-subtree-status nil)
  5843. (put 'org-cycle-subtree-status 'org-state t)
  5844. (defvar org-inlinetask-min-level)
  5845. (defun org-unlogged-message (&rest args)
  5846. "Display a message, but avoid logging it in the *Messages* buffer."
  5847. (let ((message-log-max nil))
  5848. (apply 'message args)))
  5849. ;;;###autoload
  5850. (defun org-cycle (&optional arg)
  5851. "TAB-action and visibility cycling for Org-mode.
  5852. This is the command invoked in Org-mode by the TAB key. Its main purpose
  5853. is outline visibility cycling, but it also invokes other actions
  5854. in special contexts.
  5855. - When this function is called with a prefix argument, rotate the entire
  5856. buffer through 3 states (global cycling)
  5857. 1. OVERVIEW: Show only top-level headlines.
  5858. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5859. 3. SHOW ALL: Show everything.
  5860. With a double \\[universal-argument] prefix argument, \
  5861. switch to the startup visibility,
  5862. determined by the variable `org-startup-folded', and by any VISIBILITY
  5863. properties in the buffer.
  5864. With a triple \\[universal-argument] prefix argument, \
  5865. show the entire buffer, including any drawers.
  5866. - When inside a table, re-align the table and move to the next field.
  5867. - When point is at the beginning of a headline, rotate the subtree started
  5868. by this line through 3 different states (local cycling)
  5869. 1. FOLDED: Only the main headline is shown.
  5870. 2. CHILDREN: The main headline and the direct children are shown.
  5871. From this state, you can move to one of the children
  5872. and zoom in further.
  5873. 3. SUBTREE: Show the entire subtree, including body text.
  5874. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5875. - When point is at the beginning of an empty headline and the variable
  5876. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5877. of the headline by demoting and promoting it to likely levels. This
  5878. speeds up creation document structure by pressing TAB once or several
  5879. times right after creating a new headline.
  5880. - When there is a numeric prefix, go up to a heading with level ARG, do
  5881. a `show-subtree' and return to the previous cursor position. If ARG
  5882. is negative, go up that many levels.
  5883. - When point is not at the beginning of a headline, execute the global
  5884. binding for TAB, which is re-indenting the line. See the option
  5885. `org-cycle-emulate-tab' for details.
  5886. - Special case: if point is at the beginning of the buffer and there is
  5887. no headline in line 1, this function will act as if called with prefix arg
  5888. (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
  5889. But only if also the variable `org-cycle-global-at-bob' is t."
  5890. (interactive "P")
  5891. (org-load-modules-maybe)
  5892. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5893. (and org-cycle-level-after-item/entry-creation
  5894. (or (org-cycle-level)
  5895. (org-cycle-item-indentation))))
  5896. (let* ((limit-level
  5897. (or org-cycle-max-level
  5898. (and (boundp 'org-inlinetask-min-level)
  5899. org-inlinetask-min-level
  5900. (1- org-inlinetask-min-level))))
  5901. (nstars (and limit-level
  5902. (if org-odd-levels-only
  5903. (and limit-level (1- (* limit-level 2)))
  5904. limit-level)))
  5905. (org-outline-regexp
  5906. (if (not (derived-mode-p 'org-mode))
  5907. outline-regexp
  5908. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5909. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5910. (not (looking-at org-outline-regexp))))
  5911. (org-cycle-hook
  5912. (if bob-special
  5913. (delq 'org-optimize-window-after-visibility-change
  5914. (copy-sequence org-cycle-hook))
  5915. org-cycle-hook))
  5916. (pos (point)))
  5917. (when (or bob-special (equal arg '(4)))
  5918. ;; special case: use global cycling
  5919. (setq arg t))
  5920. (cond
  5921. ((equal arg '(16))
  5922. (setq last-command 'dummy)
  5923. (org-set-startup-visibility)
  5924. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5925. ((equal arg '(64))
  5926. (outline-show-all)
  5927. (org-unlogged-message "Entire buffer visible, including drawers"))
  5928. ;; Try cdlatex TAB completion
  5929. ((org-try-cdlatex-tab))
  5930. ;; Table: enter it or move to the next field.
  5931. ((org-at-table-p 'any)
  5932. (if (org-at-table.el-p)
  5933. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5934. Use \\[org-edit-special] to edit table.el tables"))
  5935. (if arg (org-table-edit-field t)
  5936. (org-table-justify-field-maybe)
  5937. (call-interactively 'org-table-next-field))))
  5938. ((run-hook-with-args-until-success
  5939. 'org-tab-after-check-for-table-hook))
  5940. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5941. ((eq arg t) (org-cycle-internal-global))
  5942. ;; Drawers: delegate to `org-flag-drawer'.
  5943. ((save-excursion
  5944. (beginning-of-line 1)
  5945. (looking-at org-drawer-regexp))
  5946. (org-flag-drawer ; toggle block visibility
  5947. (not (get-char-property (match-end 0) 'invisible))))
  5948. ;; Show-subtree, ARG levels up from here.
  5949. ((integerp arg)
  5950. (save-excursion
  5951. (org-back-to-heading)
  5952. (outline-up-heading (if (< arg 0) (- arg)
  5953. (- (funcall outline-level) arg)))
  5954. (org-show-subtree)))
  5955. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5956. ((and (featurep 'org-inlinetask)
  5957. (org-inlinetask-at-task-p)
  5958. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5959. (org-inlinetask-toggle-visibility))
  5960. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5961. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5962. (save-excursion (move-beginning-of-line 1)
  5963. (looking-at org-outline-regexp)))
  5964. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5965. (org-cycle-internal-local))
  5966. ;; From there: TAB emulation and template completion.
  5967. (buffer-read-only (org-back-to-heading))
  5968. ((run-hook-with-args-until-success
  5969. 'org-tab-after-check-for-cycling-hook))
  5970. ((org-try-structure-completion))
  5971. ((run-hook-with-args-until-success
  5972. 'org-tab-before-tab-emulation-hook))
  5973. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5974. (or (not (bolp))
  5975. (not (looking-at org-outline-regexp))))
  5976. (call-interactively (global-key-binding "\t")))
  5977. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5978. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5979. (or (and (eq org-cycle-emulate-tab 'white)
  5980. (= (match-end 0) (point-at-eol)))
  5981. (and (eq org-cycle-emulate-tab 'whitestart)
  5982. (>= (match-end 0) pos))))
  5983. t
  5984. (eq org-cycle-emulate-tab t))
  5985. (call-interactively (global-key-binding "\t")))
  5986. (t (save-excursion
  5987. (org-back-to-heading)
  5988. (org-cycle)))))))
  5989. (defun org-cycle-internal-global ()
  5990. "Do the global cycling action."
  5991. ;; Hack to avoid display of messages for .org attachments in Gnus
  5992. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5993. (cond
  5994. ((and (eq last-command this-command)
  5995. (eq org-cycle-global-status 'overview))
  5996. ;; We just created the overview - now do table of contents
  5997. ;; This can be slow in very large buffers, so indicate action
  5998. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5999. (unless ga (org-unlogged-message "CONTENTS..."))
  6000. (org-content)
  6001. (unless ga (org-unlogged-message "CONTENTS...done"))
  6002. (setq org-cycle-global-status 'contents)
  6003. (run-hook-with-args 'org-cycle-hook 'contents))
  6004. ((and (eq last-command this-command)
  6005. (eq org-cycle-global-status 'contents))
  6006. ;; We just showed the table of contents - now show everything
  6007. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6008. (outline-show-all)
  6009. (unless ga (org-unlogged-message "SHOW ALL"))
  6010. (setq org-cycle-global-status 'all)
  6011. (run-hook-with-args 'org-cycle-hook 'all))
  6012. (t
  6013. ;; Default action: go to overview
  6014. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6015. (org-overview)
  6016. (unless ga (org-unlogged-message "OVERVIEW"))
  6017. (setq org-cycle-global-status 'overview)
  6018. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6019. (defvar org-called-with-limited-levels nil
  6020. "Non-nil when `org-with-limited-levels' is currently active.")
  6021. (defun org-cycle-internal-local ()
  6022. "Do the local cycling action."
  6023. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6024. ;; First, determine end of headline (EOH), end of subtree or item
  6025. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6026. (save-excursion
  6027. (if (org-at-item-p)
  6028. (progn
  6029. (beginning-of-line)
  6030. (setq struct (org-list-struct))
  6031. (setq eoh (point-at-eol))
  6032. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6033. (setq has-children (org-list-has-child-p (point) struct)))
  6034. (org-back-to-heading)
  6035. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6036. (setq eos (save-excursion (org-end-of-subtree t t)
  6037. (when (bolp) (backward-char)) (point)))
  6038. (setq has-children
  6039. (or (save-excursion
  6040. (let ((level (funcall outline-level)))
  6041. (outline-next-heading)
  6042. (and (org-at-heading-p t)
  6043. (> (funcall outline-level) level))))
  6044. (save-excursion
  6045. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6046. ;; Determine end invisible part of buffer (EOL)
  6047. (beginning-of-line 2)
  6048. ;; XEmacs doesn't have `next-single-char-property-change'
  6049. (if (featurep 'xemacs)
  6050. (while (and (not (eobp)) ;; this is like `next-line'
  6051. (get-char-property (1- (point)) 'invisible))
  6052. (beginning-of-line 2))
  6053. (while (and (not (eobp)) ;; this is like `next-line'
  6054. (get-char-property (1- (point)) 'invisible))
  6055. (goto-char (next-single-char-property-change (point) 'invisible))
  6056. (and (eolp) (beginning-of-line 2))))
  6057. (setq eol (point)))
  6058. ;; Find out what to do next and set `this-command'
  6059. (cond
  6060. ((= eos eoh)
  6061. ;; Nothing is hidden behind this heading
  6062. (unless (org-before-first-heading-p)
  6063. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6064. (org-unlogged-message "EMPTY ENTRY")
  6065. (setq org-cycle-subtree-status nil)
  6066. (save-excursion
  6067. (goto-char eos)
  6068. (outline-next-heading)
  6069. (when (outline-invisible-p) (org-flag-heading nil))))
  6070. ((and (or (>= eol eos)
  6071. (not (string-match "\\S-" (buffer-substring eol eos))))
  6072. (or has-children
  6073. (not (setq children-skipped
  6074. org-cycle-skip-children-state-if-no-children))))
  6075. ;; Entire subtree is hidden in one line: children view
  6076. (unless (org-before-first-heading-p)
  6077. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6078. (if (org-at-item-p)
  6079. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6080. (org-show-entry)
  6081. (org-with-limited-levels (org-show-children))
  6082. ;; FIXME: This slows down the func way too much.
  6083. ;; How keep drawers hidden in subtree anyway?
  6084. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6085. ;; (org-cycle-hide-drawers 'subtree))
  6086. ;; Fold every list in subtree to top-level items.
  6087. (when (eq org-cycle-include-plain-lists 'integrate)
  6088. (save-excursion
  6089. (org-back-to-heading)
  6090. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6091. (beginning-of-line 1)
  6092. (let* ((struct (org-list-struct))
  6093. (prevs (org-list-prevs-alist struct))
  6094. (end (org-list-get-bottom-point struct)))
  6095. (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
  6096. (org-list-get-all-items (point) struct prevs))
  6097. (goto-char (if (< end eos) end eos)))))))
  6098. (org-unlogged-message "CHILDREN")
  6099. (save-excursion
  6100. (goto-char eos)
  6101. (outline-next-heading)
  6102. (when (outline-invisible-p) (org-flag-heading nil)))
  6103. (setq org-cycle-subtree-status 'children)
  6104. (unless (org-before-first-heading-p)
  6105. (run-hook-with-args 'org-cycle-hook 'children)))
  6106. ((or children-skipped
  6107. (and (eq last-command this-command)
  6108. (eq org-cycle-subtree-status 'children)))
  6109. ;; We just showed the children, or no children are there,
  6110. ;; now show everything.
  6111. (unless (org-before-first-heading-p)
  6112. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6113. (outline-flag-region eoh eos nil)
  6114. (org-unlogged-message
  6115. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6116. (setq org-cycle-subtree-status 'subtree)
  6117. (unless (org-before-first-heading-p)
  6118. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6119. (t
  6120. ;; Default action: hide the subtree.
  6121. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6122. (outline-flag-region eoh eos t)
  6123. (org-unlogged-message "FOLDED")
  6124. (setq org-cycle-subtree-status 'folded)
  6125. (unless (org-before-first-heading-p)
  6126. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6127. ;;;###autoload
  6128. (defun org-global-cycle (&optional arg)
  6129. "Cycle the global visibility. For details see `org-cycle'.
  6130. With \\[universal-argument] prefix arg, switch to startup visibility.
  6131. With a numeric prefix, show all headlines up to that level."
  6132. (interactive "P")
  6133. (let ((org-cycle-include-plain-lists
  6134. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6135. (cond
  6136. ((integerp arg)
  6137. (outline-show-all)
  6138. (outline-hide-sublevels arg)
  6139. (setq org-cycle-global-status 'contents))
  6140. ((equal arg '(4))
  6141. (org-set-startup-visibility)
  6142. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6143. (t
  6144. (org-cycle '(4))))))
  6145. (defun org-set-startup-visibility ()
  6146. "Set the visibility required by startup options and properties."
  6147. (cond
  6148. ((eq org-startup-folded t)
  6149. (org-overview))
  6150. ((eq org-startup-folded 'content)
  6151. (org-content))
  6152. ((or (eq org-startup-folded 'showeverything)
  6153. (eq org-startup-folded nil))
  6154. (outline-show-all)))
  6155. (unless (eq org-startup-folded 'showeverything)
  6156. (when org-hide-block-startup (org-hide-block-all))
  6157. (org-set-visibility-according-to-property 'no-cleanup)
  6158. (org-cycle-hide-archived-subtrees 'all)
  6159. (org-cycle-hide-drawers 'all)
  6160. (org-cycle-show-empty-lines t)))
  6161. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6162. "Switch subtree visibilities according to :VISIBILITY: property."
  6163. (interactive)
  6164. (org-with-wide-buffer
  6165. (goto-char (point-min))
  6166. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6167. (if (not (org-at-property-p)) (outline-next-heading)
  6168. (let ((state (match-string 3)))
  6169. (save-excursion
  6170. (org-back-to-heading t)
  6171. (outline-hide-subtree)
  6172. (org-reveal)
  6173. (cond
  6174. ((equal state "folded")
  6175. (outline-hide-subtree))
  6176. ((equal state "children")
  6177. (org-show-hidden-entry)
  6178. (org-show-children))
  6179. ((equal state "content")
  6180. (save-excursion
  6181. (save-restriction
  6182. (org-narrow-to-subtree)
  6183. (org-content))))
  6184. ((member state '("all" "showall"))
  6185. (outline-show-subtree)))))))
  6186. (unless no-cleanup
  6187. (org-cycle-hide-archived-subtrees 'all)
  6188. (org-cycle-hide-drawers 'all)
  6189. (org-cycle-show-empty-lines 'all))))
  6190. ;; This function uses outline-regexp instead of the more fundamental
  6191. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6192. ;; buffers, where outline-regexp is needed.
  6193. (defun org-overview ()
  6194. "Switch to overview mode, showing only top-level headlines.
  6195. This shows all headlines with a level equal or greater than the level
  6196. of the first headline in the buffer. This is important, because if the
  6197. first headline is not level one, then (hide-sublevels 1) gives confusing
  6198. results."
  6199. (interactive)
  6200. (save-excursion
  6201. (let ((level
  6202. (save-excursion
  6203. (goto-char (point-min))
  6204. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6205. (goto-char (match-beginning 0))
  6206. (funcall outline-level)))))
  6207. (and level (outline-hide-sublevels level)))))
  6208. (defun org-content (&optional arg)
  6209. "Show all headlines in the buffer, like a table of contents.
  6210. With numerical argument N, show content up to level N."
  6211. (interactive "P")
  6212. (org-overview)
  6213. (save-excursion
  6214. ;; Visit all headings and show their offspring
  6215. (and (integerp arg) (org-overview))
  6216. (goto-char (point-max))
  6217. (catch 'exit
  6218. (while (and (progn (condition-case nil
  6219. (outline-previous-visible-heading 1)
  6220. (error (goto-char (point-min))))
  6221. t)
  6222. (looking-at org-outline-regexp))
  6223. (if (integerp arg)
  6224. (org-show-children (1- arg))
  6225. (outline-show-branches))
  6226. (when (bobp) (throw 'exit nil))))))
  6227. (defun org-optimize-window-after-visibility-change (state)
  6228. "Adjust the window after a change in outline visibility.
  6229. This function is the default value of the hook `org-cycle-hook'."
  6230. (when (get-buffer-window (current-buffer))
  6231. (cond
  6232. ((eq state 'content) nil)
  6233. ((eq state 'all) nil)
  6234. ((eq state 'folded) nil)
  6235. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6236. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6237. (defun org-remove-empty-overlays-at (pos)
  6238. "Remove outline overlays that do not contain non-white stuff."
  6239. (mapc
  6240. (lambda (o)
  6241. (and (eq 'outline (overlay-get o 'invisible))
  6242. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6243. (overlay-end o))))
  6244. (delete-overlay o)))
  6245. (overlays-at pos)))
  6246. (defun org-clean-visibility-after-subtree-move ()
  6247. "Fix visibility issues after moving a subtree."
  6248. ;; First, find a reasonable region to look at:
  6249. ;; Start two siblings above, end three below
  6250. (let* ((beg (save-excursion
  6251. (and (org-get-last-sibling)
  6252. (org-get-last-sibling))
  6253. (point)))
  6254. (end (save-excursion
  6255. (and (org-get-next-sibling)
  6256. (org-get-next-sibling)
  6257. (org-get-next-sibling))
  6258. (if (org-at-heading-p)
  6259. (point-at-eol)
  6260. (point))))
  6261. (level (looking-at "\\*+"))
  6262. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6263. (save-excursion
  6264. (save-restriction
  6265. (narrow-to-region beg end)
  6266. (when re
  6267. ;; Properly fold already folded siblings
  6268. (goto-char (point-min))
  6269. (while (re-search-forward re nil t)
  6270. (when (and (not (outline-invisible-p))
  6271. (save-excursion
  6272. (goto-char (point-at-eol)) (outline-invisible-p)))
  6273. (outline-hide-entry))))
  6274. (org-cycle-show-empty-lines 'overview)
  6275. (org-cycle-hide-drawers 'overview)))))
  6276. (defun org-cycle-show-empty-lines (state)
  6277. "Show empty lines above all visible headlines.
  6278. The region to be covered depends on STATE when called through
  6279. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6280. entire buffer covered. Note that an empty line is only shown if there
  6281. are at least `org-cycle-separator-lines' empty lines before the headline."
  6282. (when (/= org-cycle-separator-lines 0)
  6283. (save-excursion
  6284. (let* ((n (abs org-cycle-separator-lines))
  6285. (re (cond
  6286. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6287. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6288. (t (let ((ns (number-to-string (- n 2))))
  6289. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6290. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6291. beg end)
  6292. (cond
  6293. ((memq state '(overview contents t))
  6294. (setq beg (point-min) end (point-max)))
  6295. ((memq state '(children folded))
  6296. (setq beg (point)
  6297. end (progn (org-end-of-subtree t t)
  6298. (line-beginning-position 2)))))
  6299. (when beg
  6300. (goto-char beg)
  6301. (while (re-search-forward re end t)
  6302. (unless (get-char-property (match-end 1) 'invisible)
  6303. (let ((e (match-end 1))
  6304. (b (if (>= org-cycle-separator-lines 0)
  6305. (match-beginning 1)
  6306. (save-excursion
  6307. (goto-char (match-beginning 0))
  6308. (skip-chars-backward " \t\n")
  6309. (line-end-position)))))
  6310. (outline-flag-region b e nil))))))))
  6311. ;; Never hide empty lines at the end of the file.
  6312. (save-excursion
  6313. (goto-char (point-max))
  6314. (outline-previous-heading)
  6315. (outline-end-of-heading)
  6316. (when (and (looking-at "[ \t\n]+")
  6317. (= (match-end 0) (point-max)))
  6318. (outline-flag-region (point) (match-end 0) nil))))
  6319. (defun org-show-empty-lines-in-parent ()
  6320. "Move to the parent and re-show empty lines before visible headlines."
  6321. (save-excursion
  6322. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6323. (org-cycle-show-empty-lines context))))
  6324. (defun org-files-list ()
  6325. "Return `org-agenda-files' list, plus all open org-mode files.
  6326. This is useful for operations that need to scan all of a user's
  6327. open and agenda-wise Org files."
  6328. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6329. (dolist (buf (buffer-list))
  6330. (with-current-buffer buf
  6331. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6332. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6333. files))
  6334. (defsubst org-entry-beginning-position ()
  6335. "Return the beginning position of the current entry."
  6336. (save-excursion (outline-back-to-heading t) (point)))
  6337. (defsubst org-entry-end-position ()
  6338. "Return the end position of the current entry."
  6339. (save-excursion (outline-next-heading) (point)))
  6340. (defun org-cycle-hide-drawers (state &optional exceptions)
  6341. "Re-hide all drawers after a visibility state change.
  6342. When non-nil, optional argument EXCEPTIONS is a list of strings
  6343. specifying which drawers should not be hidden."
  6344. (when (and (derived-mode-p 'org-mode)
  6345. (not (memq state '(overview folded contents))))
  6346. (save-excursion
  6347. (let* ((globalp (memq state '(contents all)))
  6348. (beg (if globalp (point-min) (point)))
  6349. (end (if globalp (point-max)
  6350. (if (eq state 'children)
  6351. (save-excursion (outline-next-heading) (point))
  6352. (org-end-of-subtree t)))))
  6353. (goto-char beg)
  6354. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6355. (unless (member-ignore-case (match-string 1) exceptions)
  6356. (let ((drawer (org-element-at-point)))
  6357. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6358. (org-flag-drawer t drawer)
  6359. ;; Make sure to skip drawer entirely or we might flag
  6360. ;; it another time when matching its ending line with
  6361. ;; `org-drawer-regexp'.
  6362. (goto-char (org-element-property :end drawer))))))))))
  6363. (defun org-flag-drawer (flag &optional element)
  6364. "When FLAG is non-nil, hide the drawer we are at.
  6365. Otherwise make it visible. When optional argument ELEMENT is
  6366. a parsed drawer, as returned by `org-element-at-point', hide or
  6367. show that drawer instead."
  6368. (when (save-excursion
  6369. (beginning-of-line)
  6370. (org-looking-at-p org-drawer-regexp))
  6371. (let ((drawer (or element (org-element-at-point))))
  6372. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6373. (let ((post (org-element-property :post-affiliated drawer)))
  6374. (save-excursion
  6375. (outline-flag-region
  6376. (progn (goto-char post) (line-end-position))
  6377. (progn (goto-char (org-element-property :end drawer))
  6378. (skip-chars-backward " \r\t\n")
  6379. (line-end-position))
  6380. flag))
  6381. ;; When the drawer is hidden away, make sure point lies in
  6382. ;; a visible part of the buffer.
  6383. (when (and flag (> (line-beginning-position) post))
  6384. (goto-char post)))))))
  6385. (defun org-subtree-end-visible-p ()
  6386. "Is the end of the current subtree visible?"
  6387. (pos-visible-in-window-p
  6388. (save-excursion (org-end-of-subtree t) (point))))
  6389. (defun org-first-headline-recenter ()
  6390. "Move cursor to the first headline and recenter the headline."
  6391. (goto-char (point-min))
  6392. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6393. (set-window-start (selected-window) (point-at-bol))))
  6394. ;;; Saving and restoring visibility
  6395. (defun org-outline-overlay-data (&optional use-markers)
  6396. "Return a list of the locations of all outline overlays.
  6397. These are overlays with the `invisible' property value `outline'.
  6398. The return value is a list of cons cells, with start and stop
  6399. positions for each overlay.
  6400. If USE-MARKERS is set, return the positions as markers."
  6401. (let (beg end)
  6402. (save-excursion
  6403. (save-restriction
  6404. (widen)
  6405. (delq nil
  6406. (mapcar (lambda (o)
  6407. (when (eq (overlay-get o 'invisible) 'outline)
  6408. (setq beg (overlay-start o)
  6409. end (overlay-end o))
  6410. (and beg end (> end beg)
  6411. (if use-markers
  6412. (cons (copy-marker beg)
  6413. (copy-marker end t))
  6414. (cons beg end)))))
  6415. (overlays-in (point-min) (point-max))))))))
  6416. (defun org-set-outline-overlay-data (data)
  6417. "Create visibility overlays for all positions in DATA.
  6418. DATA should have been made by `org-outline-overlay-data'."
  6419. (org-with-wide-buffer
  6420. (outline-show-all)
  6421. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6422. ;;; Folding of blocks
  6423. (defvar-local org-hide-block-overlays nil
  6424. "Overlays hiding blocks.")
  6425. (defun org-block-map (function &optional start end)
  6426. "Call FUNCTION at the head of all source blocks in the current buffer.
  6427. Optional arguments START and END can be used to limit the range."
  6428. (let ((start (or start (point-min)))
  6429. (end (or end (point-max))))
  6430. (save-excursion
  6431. (goto-char start)
  6432. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6433. (save-excursion
  6434. (save-match-data
  6435. (goto-char (match-beginning 0))
  6436. (funcall function)))))))
  6437. (defun org-hide-block-toggle-all ()
  6438. "Toggle the visibility of all blocks in the current buffer."
  6439. (org-block-map 'org-hide-block-toggle))
  6440. (defun org-hide-block-all ()
  6441. "Fold all blocks in the current buffer."
  6442. (interactive)
  6443. (org-show-block-all)
  6444. (org-block-map 'org-hide-block-toggle-maybe))
  6445. (defun org-show-block-all ()
  6446. "Unfold all blocks in the current buffer."
  6447. (interactive)
  6448. (mapc 'delete-overlay org-hide-block-overlays)
  6449. (setq org-hide-block-overlays nil))
  6450. (defun org-hide-block-toggle-maybe ()
  6451. "Toggle visibility of block at point.
  6452. Unlike to `org-hide-block-toggle', this function does not throw
  6453. an error. Return a non-nil value when toggling is successful."
  6454. (interactive)
  6455. (ignore-errors (org-hide-block-toggle)))
  6456. (defun org-hide-block-toggle (&optional force)
  6457. "Toggle the visibility of the current block.
  6458. When optional argument FORCE is `off', make block visible. If it
  6459. is non-nil, hide it unconditionally. Throw an error when not at
  6460. a block. Return a non-nil value when toggling is successful."
  6461. (interactive)
  6462. (let ((element (org-element-at-point)))
  6463. (unless (memq (org-element-type element)
  6464. '(center-block comment-block dynamic-block example-block
  6465. export-block quote-block special-block
  6466. src-block verse-block))
  6467. (user-error "Not at a block"))
  6468. (let* ((start (save-excursion
  6469. (goto-char (org-element-property :post-affiliated element))
  6470. (line-end-position)))
  6471. (end (save-excursion
  6472. (goto-char (org-element-property :end element))
  6473. (skip-chars-backward " \r\t\n")
  6474. (line-end-position)))
  6475. (overlays (overlays-at start)))
  6476. (cond
  6477. ;; Do nothing when not before or at the block opening line or
  6478. ;; at the block closing line.
  6479. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6480. ((and (not (eq force 'off))
  6481. (not (memq t (mapcar
  6482. (lambda (o)
  6483. (eq (overlay-get o 'invisible) 'org-hide-block))
  6484. overlays))))
  6485. (let ((ov (make-overlay start end)))
  6486. (overlay-put ov 'invisible 'org-hide-block)
  6487. ;; Make the block accessible to `isearch'.
  6488. (overlay-put
  6489. ov 'isearch-open-invisible
  6490. (lambda (ov)
  6491. (when (memq ov org-hide-block-overlays)
  6492. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6493. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6494. (delete-overlay ov))))
  6495. (push ov org-hide-block-overlays)
  6496. ;; When the block is hidden away, make sure point is left in
  6497. ;; a visible part of the buffer.
  6498. (when (> (line-beginning-position) start)
  6499. (goto-char start)
  6500. (beginning-of-line))
  6501. ;; Signal successful toggling.
  6502. t))
  6503. ((or (not force) (eq force 'off))
  6504. (dolist (ov overlays t)
  6505. (when (memq ov org-hide-block-overlays)
  6506. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6507. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6508. (delete-overlay ov))))))))
  6509. ;; org-tab-after-check-for-cycling-hook
  6510. (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
  6511. ;; Remove overlays when changing major mode
  6512. (add-hook 'org-mode-hook
  6513. (lambda () (org-add-hook 'change-major-mode-hook
  6514. 'org-show-block-all 'append 'local)))
  6515. ;;; Org-goto
  6516. (defvar org-goto-window-configuration nil)
  6517. (defvar org-goto-marker nil)
  6518. (defvar org-goto-map)
  6519. (defun org-goto-map ()
  6520. "Set the keymap `org-goto'."
  6521. (setq org-goto-map
  6522. (let ((map (make-sparse-keymap)))
  6523. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6524. mouse-drag-region universal-argument org-occur)))
  6525. (dolist (cmd cmds)
  6526. (substitute-key-definition cmd cmd map global-map)))
  6527. (suppress-keymap map)
  6528. (org-defkey map "\C-m" 'org-goto-ret)
  6529. (org-defkey map [(return)] 'org-goto-ret)
  6530. (org-defkey map [(left)] 'org-goto-left)
  6531. (org-defkey map [(right)] 'org-goto-right)
  6532. (org-defkey map [(control ?g)] 'org-goto-quit)
  6533. (org-defkey map "\C-i" 'org-cycle)
  6534. (org-defkey map [(tab)] 'org-cycle)
  6535. (org-defkey map [(down)] 'outline-next-visible-heading)
  6536. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6537. (if org-goto-auto-isearch
  6538. (if (fboundp 'define-key-after)
  6539. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6540. nil)
  6541. (org-defkey map "q" 'org-goto-quit)
  6542. (org-defkey map "n" 'outline-next-visible-heading)
  6543. (org-defkey map "p" 'outline-previous-visible-heading)
  6544. (org-defkey map "f" 'outline-forward-same-level)
  6545. (org-defkey map "b" 'outline-backward-same-level)
  6546. (org-defkey map "u" 'outline-up-heading))
  6547. (org-defkey map "/" 'org-occur)
  6548. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6549. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6550. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6551. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6552. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6553. map)))
  6554. (defconst org-goto-help
  6555. "Browse buffer copy, to find location or copy text.%s
  6556. RET=jump to location C-g=quit and return to previous location
  6557. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6558. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6559. (defun org-goto (&optional alternative-interface)
  6560. "Look up a different location in the current file, keeping current visibility.
  6561. When you want look-up or go to a different location in a
  6562. document, the fastest way is often to fold the entire buffer and
  6563. then dive into the tree. This method has the disadvantage, that
  6564. the previous location will be folded, which may not be what you
  6565. want.
  6566. This command works around this by showing a copy of the current
  6567. buffer in an indirect buffer, in overview mode. You can dive
  6568. into the tree in that copy, use org-occur and incremental search
  6569. to find a location. When pressing RET or `Q', the command
  6570. returns to the original buffer in which the visibility is still
  6571. unchanged. After RET it will also jump to the location selected
  6572. in the indirect buffer and expose the headline hierarchy above.
  6573. With a prefix argument, use the alternative interface: e.g., if
  6574. `org-goto-interface' is `outline' use `outline-path-completion'."
  6575. (interactive "P")
  6576. (org-goto-map)
  6577. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6578. (org-refile-use-outline-path t)
  6579. (org-refile-target-verify-function nil)
  6580. (interface
  6581. (if (not alternative-interface)
  6582. org-goto-interface
  6583. (if (eq org-goto-interface 'outline)
  6584. 'outline-path-completion
  6585. 'outline)))
  6586. (org-goto-start-pos (point))
  6587. (selected-point
  6588. (if (eq interface 'outline)
  6589. (car (org-get-location (current-buffer) org-goto-help))
  6590. (let ((pa (org-refile-get-location "Goto" nil nil t)))
  6591. (org-refile-check-position pa)
  6592. (nth 3 pa)))))
  6593. (if selected-point
  6594. (progn
  6595. (org-mark-ring-push org-goto-start-pos)
  6596. (goto-char selected-point)
  6597. (when (or (outline-invisible-p) (org-invisible-p2))
  6598. (org-show-context 'org-goto)))
  6599. (message "Quit"))))
  6600. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6601. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6602. (defvar org-goto-local-auto-isearch-map) ; defined below
  6603. (defun org-get-location (_buf help)
  6604. "Let the user select a location in current buffer.
  6605. This function uses a recursive edit. It returns the selected position
  6606. or nil."
  6607. (org-no-popups
  6608. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6609. (isearch-hide-immediately nil)
  6610. (isearch-search-fun-function
  6611. (lambda () 'org-goto-local-search-headings))
  6612. (org-goto-selected-point org-goto-exit-command))
  6613. (save-excursion
  6614. (save-window-excursion
  6615. (delete-other-windows)
  6616. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6617. (org-pop-to-buffer-same-window
  6618. (condition-case nil
  6619. (make-indirect-buffer (current-buffer) "*org-goto*")
  6620. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6621. (with-output-to-temp-buffer "*Org Help*"
  6622. (princ (format help (if org-goto-auto-isearch
  6623. " Just type for auto-isearch."
  6624. " n/p/f/b/u to navigate, q to quit."))))
  6625. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6626. (setq buffer-read-only nil)
  6627. (let ((org-startup-truncated t)
  6628. (org-startup-folded nil)
  6629. (org-startup-align-all-tables nil))
  6630. (org-mode)
  6631. (org-overview))
  6632. (setq buffer-read-only t)
  6633. (if (and (boundp 'org-goto-start-pos)
  6634. (integer-or-marker-p org-goto-start-pos))
  6635. (progn (goto-char org-goto-start-pos)
  6636. (when (outline-invisible-p)
  6637. (org-show-set-visibility 'lineage)))
  6638. (goto-char (point-min)))
  6639. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6640. (message "Select location and press RET")
  6641. (use-local-map org-goto-map)
  6642. (recursive-edit)))
  6643. (kill-buffer "*org-goto*")
  6644. (cons org-goto-selected-point org-goto-exit-command))))
  6645. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6646. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6647. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6648. (if (fboundp 'isearch-other-control-char)
  6649. (progn
  6650. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6651. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6652. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6653. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6654. (define-key org-goto-local-auto-isearch-map [return] nil))
  6655. (defun org-goto-local-search-headings (string bound noerror)
  6656. "Search and make sure that any matches are in headlines."
  6657. (catch 'return
  6658. (while (if isearch-forward
  6659. (search-forward string bound noerror)
  6660. (search-backward string bound noerror))
  6661. (when (save-match-data
  6662. (and (save-excursion
  6663. (beginning-of-line)
  6664. (looking-at org-complex-heading-regexp))
  6665. (or (not (match-beginning 5))
  6666. (< (point) (match-beginning 5)))))
  6667. (throw 'return (point))))))
  6668. (defun org-goto-local-auto-isearch ()
  6669. "Start isearch."
  6670. (interactive)
  6671. (goto-char (point-min))
  6672. (let ((keys (this-command-keys)))
  6673. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6674. (isearch-mode t)
  6675. (isearch-process-search-char (string-to-char keys)))))
  6676. (defun org-goto-ret (&optional _arg)
  6677. "Finish `org-goto' by going to the new location."
  6678. (interactive "P")
  6679. (setq org-goto-selected-point (point))
  6680. (setq org-goto-exit-command 'return)
  6681. (throw 'exit nil))
  6682. (defun org-goto-left ()
  6683. "Finish `org-goto' by going to the new location."
  6684. (interactive)
  6685. (if (org-at-heading-p)
  6686. (progn
  6687. (beginning-of-line 1)
  6688. (setq org-goto-selected-point (point)
  6689. org-goto-exit-command 'left)
  6690. (throw 'exit nil))
  6691. (user-error "Not on a heading")))
  6692. (defun org-goto-right ()
  6693. "Finish `org-goto' by going to the new location."
  6694. (interactive)
  6695. (if (org-at-heading-p)
  6696. (progn
  6697. (setq org-goto-selected-point (point)
  6698. org-goto-exit-command 'right)
  6699. (throw 'exit nil))
  6700. (user-error "Not on a heading")))
  6701. (defun org-goto-quit ()
  6702. "Finish `org-goto' without cursor motion."
  6703. (interactive)
  6704. (setq org-goto-selected-point nil)
  6705. (setq org-goto-exit-command 'quit)
  6706. (throw 'exit nil))
  6707. ;;; Indirect buffer display of subtrees
  6708. (defvar org-indirect-dedicated-frame nil
  6709. "This is the frame being used for indirect tree display.")
  6710. (defvar org-last-indirect-buffer nil)
  6711. (defun org-tree-to-indirect-buffer (&optional arg)
  6712. "Create indirect buffer and narrow it to current subtree.
  6713. With a numerical prefix ARG, go up to this level and then take that tree.
  6714. If ARG is negative, go up that many levels.
  6715. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6716. indirect buffer previously made with this command, to avoid proliferation of
  6717. indirect buffers. However, when you call the command with a \
  6718. \\[universal-argument] prefix, or
  6719. when `org-indirect-buffer-display' is `new-frame', the last buffer
  6720. is kept so that you can work with several indirect buffers at the same time.
  6721. If `org-indirect-buffer-display' is `dedicated-frame', the \
  6722. \\[universal-argument] prefix also
  6723. requests that a new frame be made for the new buffer, so that the dedicated
  6724. frame is not changed."
  6725. (interactive "P")
  6726. (let ((cbuf (current-buffer))
  6727. (cwin (selected-window))
  6728. (pos (point))
  6729. beg end level heading ibuf)
  6730. (save-excursion
  6731. (org-back-to-heading t)
  6732. (when (numberp arg)
  6733. (setq level (org-outline-level))
  6734. (when (< arg 0) (setq arg (+ level arg)))
  6735. (while (> (setq level (org-outline-level)) arg)
  6736. (org-up-heading-safe)))
  6737. (setq beg (point)
  6738. heading (org-get-heading 'no-tags))
  6739. (org-end-of-subtree t t)
  6740. (when (org-at-heading-p) (backward-char 1))
  6741. (setq end (point)))
  6742. (when (and (buffer-live-p org-last-indirect-buffer)
  6743. (not (eq org-indirect-buffer-display 'new-frame))
  6744. (not arg))
  6745. (kill-buffer org-last-indirect-buffer))
  6746. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6747. org-last-indirect-buffer ibuf)
  6748. (cond
  6749. ((or (eq org-indirect-buffer-display 'new-frame)
  6750. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6751. (select-frame (make-frame))
  6752. (delete-other-windows)
  6753. (org-pop-to-buffer-same-window ibuf)
  6754. (org-set-frame-title heading))
  6755. ((eq org-indirect-buffer-display 'dedicated-frame)
  6756. (raise-frame
  6757. (select-frame (or (and org-indirect-dedicated-frame
  6758. (frame-live-p org-indirect-dedicated-frame)
  6759. org-indirect-dedicated-frame)
  6760. (setq org-indirect-dedicated-frame (make-frame)))))
  6761. (delete-other-windows)
  6762. (org-pop-to-buffer-same-window ibuf)
  6763. (org-set-frame-title (concat "Indirect: " heading)))
  6764. ((eq org-indirect-buffer-display 'current-window)
  6765. (org-pop-to-buffer-same-window ibuf))
  6766. ((eq org-indirect-buffer-display 'other-window)
  6767. (pop-to-buffer ibuf))
  6768. (t (error "Invalid value")))
  6769. (when (featurep 'xemacs)
  6770. (save-excursion (org-mode) (turn-on-font-lock)))
  6771. (narrow-to-region beg end)
  6772. (outline-show-all)
  6773. (goto-char pos)
  6774. (run-hook-with-args 'org-cycle-hook 'all)
  6775. (and (window-live-p cwin) (select-window cwin))))
  6776. (defun org-get-indirect-buffer (&optional buffer heading)
  6777. (setq buffer (or buffer (current-buffer)))
  6778. (let ((n 1) (base (buffer-name buffer)) bname)
  6779. (while (buffer-live-p
  6780. (get-buffer
  6781. (setq bname
  6782. (concat base "-"
  6783. (if heading (concat heading "-" (number-to-string n))
  6784. (number-to-string n))))))
  6785. (setq n (1+ n)))
  6786. (condition-case nil
  6787. (make-indirect-buffer buffer bname 'clone)
  6788. (error (make-indirect-buffer buffer bname)))))
  6789. (defun org-set-frame-title (title)
  6790. "Set the title of the current frame to the string TITLE."
  6791. ;; FIXME: how to name a single frame in XEmacs???
  6792. (unless (featurep 'xemacs)
  6793. (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
  6794. ;;;; Structure editing
  6795. ;;; Inserting headlines
  6796. (defun org--line-empty-p (n)
  6797. "Is the Nth next line empty?
  6798. Counts the current line as N = 1 and the previous line as N = 0;
  6799. see `beginning-of-line'."
  6800. (save-excursion
  6801. (and (not (bobp))
  6802. (or (beginning-of-line n) t)
  6803. (save-match-data
  6804. (looking-at "[ \t]*$")))))
  6805. (defun org-previous-line-empty-p ()
  6806. "Is the previous line a blank line?
  6807. When NEXT is non-nil, check the next line instead."
  6808. (org--line-empty-p 0))
  6809. (defun org-next-line-empty-p ()
  6810. "Is the previous line a blank line?
  6811. When NEXT is non-nil, check the next line instead."
  6812. (org--line-empty-p 2))
  6813. (defun org-insert-heading (&optional arg invisible-ok top)
  6814. "Insert a new heading or an item with the same depth at point.
  6815. If point is at the beginning of a heading or a list item, insert
  6816. a new heading or a new item above the current one. If point is
  6817. at the beginning of a normal line, turn the line into a heading.
  6818. If point is in the middle of a headline or a list item, split the
  6819. headline or the item and create a new headline/item with the text
  6820. in the current line after point \(see `org-M-RET-may-split-line'
  6821. on how to modify this behavior).
  6822. With one universal prefix argument, set the user option
  6823. `org-insert-heading-respect-content' to t for the duration of
  6824. the command. This modifies the behavior described above in this
  6825. ways: on list items and at the beginning of normal lines, force
  6826. the insertion of a heading after the current subtree.
  6827. With two universal prefix arguments, insert the heading at the
  6828. end of the grandparent subtree. For example, if point is within
  6829. a 2nd-level heading, then it will insert a 2nd-level heading at
  6830. the end of the 1st-level parent heading.
  6831. If point is at the beginning of a headline, insert a sibling
  6832. before the current headline. If point is not at the beginning,
  6833. split the line and create a new headline with the text in the
  6834. current line after point \(see `org-M-RET-may-split-line' on how
  6835. to modify this behavior).
  6836. If point is at the beginning of a normal line, turn this line
  6837. into a heading.
  6838. When INVISIBLE-OK is set, stop at invisible headlines when going
  6839. back. This is important for non-interactive uses of the
  6840. command.
  6841. When optional argument TOP is non-nil, insert a level 1 heading,
  6842. unconditionally."
  6843. (interactive "P")
  6844. (when (org-called-interactively-p 'any) (org-reveal))
  6845. (let ((itemp (and (not top) (org-in-item-p)))
  6846. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  6847. (respect-content (or org-insert-heading-respect-content
  6848. (equal arg '(4))))
  6849. (initial-content ""))
  6850. (cond
  6851. ((or (= (buffer-size) 0)
  6852. (and (not (save-excursion
  6853. (and (ignore-errors (org-back-to-heading invisible-ok))
  6854. (org-at-heading-p))))
  6855. (or arg (not itemp))))
  6856. ;; At beginning of buffer or so high up that only a heading
  6857. ;; makes sense.
  6858. (cond ((and (bolp) (not respect-content)) (insert "* "))
  6859. ((not respect-content)
  6860. (unless may-split (end-of-line))
  6861. (insert "\n* "))
  6862. ((re-search-forward org-outline-regexp-bol nil t)
  6863. (beginning-of-line)
  6864. (insert "* \n")
  6865. (backward-char))
  6866. (t (goto-char (point-max))
  6867. (insert "\n* ")))
  6868. (run-hooks 'org-insert-heading-hook))
  6869. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  6870. (t
  6871. ;; Maybe move at the end of the subtree
  6872. (when (equal arg '(16))
  6873. (org-up-heading-safe)
  6874. (org-end-of-subtree t))
  6875. ;; Insert a heading
  6876. (save-restriction
  6877. (widen)
  6878. (let* ((level nil)
  6879. (on-heading (org-at-heading-p))
  6880. (empty-line-p (if on-heading
  6881. (org-previous-line-empty-p)
  6882. ;; We will decide later
  6883. nil))
  6884. ;; Get a level string to fall back on.
  6885. (fix-level
  6886. (if (org-before-first-heading-p) "*"
  6887. (save-excursion
  6888. (org-back-to-heading t)
  6889. (when (org-previous-line-empty-p) (setq empty-line-p t))
  6890. (looking-at org-outline-regexp)
  6891. (make-string (1- (length (match-string 0))) ?*))))
  6892. (stars
  6893. (save-excursion
  6894. (condition-case nil
  6895. (if top "* "
  6896. (org-back-to-heading invisible-ok)
  6897. (when (and (not on-heading)
  6898. (featurep 'org-inlinetask)
  6899. (integerp org-inlinetask-min-level)
  6900. (>= (length (match-string 0))
  6901. org-inlinetask-min-level))
  6902. ;; Find a heading level before the inline
  6903. ;; task.
  6904. (while (and (setq level (org-up-heading-safe))
  6905. (>= level org-inlinetask-min-level)))
  6906. (if (org-at-heading-p)
  6907. (org-back-to-heading invisible-ok)
  6908. (error "This should not happen")))
  6909. (unless (and (save-excursion
  6910. (save-match-data
  6911. (org-backward-heading-same-level
  6912. 1 invisible-ok))
  6913. (= (point) (match-beginning 0)))
  6914. (not (org-next-line-empty-p)))
  6915. (setq empty-line-p (or empty-line-p
  6916. (org-previous-line-empty-p))))
  6917. (match-string 0))
  6918. (error (or fix-level "* ")))))
  6919. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  6920. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  6921. ;; If we insert after content, move there and clean up
  6922. ;; whitespace.
  6923. (when (and respect-content
  6924. (not (org-looking-at-p org-outline-regexp-bol)))
  6925. (if (not (org-before-first-heading-p))
  6926. (org-end-of-subtree nil t)
  6927. (re-search-forward org-outline-regexp-bol)
  6928. (beginning-of-line 0))
  6929. (skip-chars-backward " \r\t\n")
  6930. (and (not (org-looking-back "^\\*+" (line-beginning-position)))
  6931. (looking-at "[ \t]+") (replace-match ""))
  6932. (unless (eobp) (forward-char 1))
  6933. (when (looking-at "^\\*")
  6934. (unless (bobp) (backward-char 1))
  6935. (insert "\n")))
  6936. ;; If we are splitting, grab the text that should be moved
  6937. ;; to the new headline.
  6938. (when may-split
  6939. (if (org-at-heading-p)
  6940. ;; This is a heading: split intelligently (keeping
  6941. ;; tags).
  6942. (let ((pos (point)))
  6943. (beginning-of-line)
  6944. (unless (looking-at org-complex-heading-regexp)
  6945. (error "This should not happen"))
  6946. (when (and (match-beginning 4)
  6947. (> pos (match-beginning 4))
  6948. (< pos (match-end 4)))
  6949. (setq initial-content (buffer-substring pos (match-end 4)))
  6950. (goto-char pos)
  6951. (delete-region (point) (match-end 4))
  6952. (if (looking-at "[ \t]*$")
  6953. (replace-match "")
  6954. (insert (make-string (length initial-content) ?\s)))
  6955. (setq initial-content (org-trim initial-content)))
  6956. (goto-char pos))
  6957. ;; A normal line.
  6958. (setq initial-content
  6959. (org-trim
  6960. (delete-and-extract-region (point) (line-end-position))))))
  6961. ;; If we are at the beginning of the line, insert before it.
  6962. ;; Otherwise, after it.
  6963. (cond
  6964. ((and (bolp) (looking-at "[ \t]*$")))
  6965. ((bolp) (save-excursion (insert "\n")))
  6966. (t (end-of-line)
  6967. (insert "\n")))
  6968. ;; Insert the new heading
  6969. (insert stars)
  6970. (just-one-space)
  6971. (insert initial-content)
  6972. (unless (and blank (org-previous-line-empty-p))
  6973. (org-N-empty-lines-before-current (if blank 1 0)))
  6974. ;; Adjust visibility, which may be messed up if we removed
  6975. ;; blank lines while previous entry was hidden.
  6976. (let ((bol (line-beginning-position)))
  6977. (dolist (o (overlays-at (1- bol)))
  6978. (when (and (eq (overlay-get o 'invisible) 'outline)
  6979. (eq (overlay-end o) bol))
  6980. (move-overlay o (overlay-start o) (1- bol)))))
  6981. (run-hooks 'org-insert-heading-hook)))))))
  6982. (defun org-N-empty-lines-before-current (N)
  6983. "Make the number of empty lines before current exactly N.
  6984. So this will delete or add empty lines."
  6985. (save-excursion
  6986. (beginning-of-line)
  6987. (let ((p (point)))
  6988. (skip-chars-backward " \r\t\n")
  6989. (unless (bolp) (forward-line))
  6990. (delete-region (point) p))
  6991. (when (> N 0) (insert (make-string N ?\n)))))
  6992. (defun org-get-heading (&optional no-tags no-todo)
  6993. "Return the heading of the current entry, without the stars.
  6994. When NO-TAGS is non-nil, don't include tags.
  6995. When NO-TODO is non-nil, don't include TODO keywords."
  6996. (save-excursion
  6997. (org-back-to-heading t)
  6998. (cond
  6999. ((and no-tags no-todo)
  7000. (looking-at org-complex-heading-regexp)
  7001. (match-string 4))
  7002. (no-tags
  7003. (looking-at (concat org-outline-regexp
  7004. "\\(.*?\\)"
  7005. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7006. (match-string 1))
  7007. (no-todo
  7008. (looking-at org-todo-line-regexp)
  7009. (match-string 3))
  7010. (t (looking-at org-heading-regexp)
  7011. (match-string 2)))))
  7012. (defvar orgstruct-mode) ; defined below
  7013. (defun org-heading-components ()
  7014. "Return the components of the current heading.
  7015. This is a list with the following elements:
  7016. - the level as an integer
  7017. - the reduced level, different if `org-odd-levels-only' is set.
  7018. - the TODO keyword, or nil
  7019. - the priority character, like ?A, or nil if no priority is given
  7020. - the headline text itself, or the tags string if no headline text
  7021. - the tags string, or nil."
  7022. (save-excursion
  7023. (org-back-to-heading t)
  7024. (when (let (case-fold-search)
  7025. (looking-at
  7026. (if orgstruct-mode
  7027. org-heading-regexp
  7028. org-complex-heading-regexp)))
  7029. (if orgstruct-mode
  7030. (list (length (match-string 1))
  7031. (org-reduced-level (length (match-string 1)))
  7032. nil
  7033. nil
  7034. (match-string 2)
  7035. nil)
  7036. (list (length (match-string 1))
  7037. (org-reduced-level (length (match-string 1)))
  7038. (org-match-string-no-properties 2)
  7039. (and (match-end 3) (aref (match-string 3) 2))
  7040. (org-match-string-no-properties 4)
  7041. (org-match-string-no-properties 5))))))
  7042. (defun org-get-entry ()
  7043. "Get the entry text, after heading, entire subtree."
  7044. (save-excursion
  7045. (org-back-to-heading t)
  7046. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7047. (defun org-insert-heading-after-current ()
  7048. "Insert a new heading with same level as current, after current subtree."
  7049. (interactive)
  7050. (org-back-to-heading)
  7051. (org-insert-heading)
  7052. (org-move-subtree-down)
  7053. (end-of-line 1))
  7054. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7055. "Insert heading with `org-insert-heading-respect-content' set to t."
  7056. (interactive)
  7057. (org-insert-heading '(4) invisible-ok))
  7058. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7059. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7060. (interactive)
  7061. (org-insert-todo-heading force-state '(4)))
  7062. (defun org-insert-todo-heading (arg &optional force-heading)
  7063. "Insert a new heading with the same level and TODO state as current heading.
  7064. If the heading has no TODO state, or if the state is DONE, use the first
  7065. state (TODO by default). Also with one prefix arg, force first state. With
  7066. two prefix args, force inserting at the end of the parent subtree."
  7067. (interactive "P")
  7068. (when (or force-heading (not (org-insert-item 'checkbox)))
  7069. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7070. force-heading))
  7071. (save-excursion
  7072. (org-back-to-heading)
  7073. (outline-previous-heading)
  7074. (looking-at org-todo-line-regexp))
  7075. (let*
  7076. ((new-mark-x
  7077. (if (or (equal arg '(4))
  7078. (not (match-beginning 2))
  7079. (member (match-string 2) org-done-keywords))
  7080. (car org-todo-keywords-1)
  7081. (match-string 2)))
  7082. (new-mark
  7083. (or
  7084. (run-hook-with-args-until-success
  7085. 'org-todo-get-default-hook new-mark-x nil)
  7086. new-mark-x)))
  7087. (beginning-of-line 1)
  7088. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7089. (if org-treat-insert-todo-heading-as-state-change
  7090. (org-todo new-mark)
  7091. (insert new-mark " "))))
  7092. (when org-provide-todo-statistics
  7093. (org-update-parent-todo-statistics))))
  7094. (defun org-insert-subheading (arg)
  7095. "Insert a new subheading and demote it.
  7096. Works for outline headings and for plain lists alike."
  7097. (interactive "P")
  7098. (org-insert-heading arg)
  7099. (cond
  7100. ((org-at-heading-p) (org-do-demote))
  7101. ((org-at-item-p) (org-indent-item))))
  7102. (defun org-insert-todo-subheading (arg)
  7103. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7104. Works for outline headings and for plain lists alike."
  7105. (interactive "P")
  7106. (org-insert-todo-heading arg)
  7107. (cond
  7108. ((org-at-heading-p) (org-do-demote))
  7109. ((org-at-item-p) (org-indent-item))))
  7110. ;;; Promotion and Demotion
  7111. (defvar org-after-demote-entry-hook nil
  7112. "Hook run after an entry has been demoted.
  7113. The cursor will be at the beginning of the entry.
  7114. When a subtree is being demoted, the hook will be called for each node.")
  7115. (defvar org-after-promote-entry-hook nil
  7116. "Hook run after an entry has been promoted.
  7117. The cursor will be at the beginning of the entry.
  7118. When a subtree is being promoted, the hook will be called for each node.")
  7119. (defun org-promote-subtree ()
  7120. "Promote the entire subtree.
  7121. See also `org-promote'."
  7122. (interactive)
  7123. (save-excursion
  7124. (org-with-limited-levels (org-map-tree 'org-promote)))
  7125. (org-fix-position-after-promote))
  7126. (defun org-demote-subtree ()
  7127. "Demote the entire subtree.
  7128. See `org-demote' and `org-promote'."
  7129. (interactive)
  7130. (save-excursion
  7131. (org-with-limited-levels (org-map-tree 'org-demote)))
  7132. (org-fix-position-after-promote))
  7133. (defun org-do-promote ()
  7134. "Promote the current heading higher up the tree.
  7135. If the region is active in `transient-mark-mode', promote all
  7136. headings in the region."
  7137. (interactive)
  7138. (save-excursion
  7139. (if (org-region-active-p)
  7140. (org-map-region 'org-promote (region-beginning) (region-end))
  7141. (org-promote)))
  7142. (org-fix-position-after-promote))
  7143. (defun org-do-demote ()
  7144. "Demote the current heading lower down the tree.
  7145. If the region is active in `transient-mark-mode', demote all
  7146. headings in the region."
  7147. (interactive)
  7148. (save-excursion
  7149. (if (org-region-active-p)
  7150. (org-map-region 'org-demote (region-beginning) (region-end))
  7151. (org-demote)))
  7152. (org-fix-position-after-promote))
  7153. (defun org-fix-position-after-promote ()
  7154. "Fix cursor position and indentation after demoting/promoting."
  7155. (let ((pos (point)))
  7156. (when (save-excursion
  7157. (beginning-of-line 1)
  7158. (looking-at org-todo-line-regexp)
  7159. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7160. (cond ((eobp) (insert " "))
  7161. ((eolp) (insert " "))
  7162. ((equal (char-after) ?\ ) (forward-char 1))))))
  7163. (defun org-current-level ()
  7164. "Return the level of the current entry, or nil if before the first headline.
  7165. The level is the number of stars at the beginning of the
  7166. headline. Use `org-reduced-level' to remove the effect of
  7167. `org-odd-levels'. Unlike to `org-outline-level', this function
  7168. ignores inlinetasks."
  7169. (let ((level (org-with-limited-levels (org-outline-level))))
  7170. (and (> level 0) level)))
  7171. (defun org-get-previous-line-level ()
  7172. "Return the outline depth of the last headline before the current line.
  7173. Returns 0 for the first headline in the buffer, and nil if before the
  7174. first headline."
  7175. (and (org-current-level)
  7176. (or (and (/= (line-beginning-position) (point-min))
  7177. (save-excursion (beginning-of-line 0) (org-current-level)))
  7178. 0)))
  7179. (defun org-reduced-level (l)
  7180. "Compute the effective level of a heading.
  7181. This takes into account the setting of `org-odd-levels-only'."
  7182. (cond
  7183. ((zerop l) 0)
  7184. (org-odd-levels-only (1+ (floor (/ l 2))))
  7185. (t l)))
  7186. (defun org-level-increment ()
  7187. "Return the number of stars that will be added or removed at a
  7188. time to headlines when structure editing, based on the value of
  7189. `org-odd-levels-only'."
  7190. (if org-odd-levels-only 2 1))
  7191. (defun org-get-valid-level (level &optional change)
  7192. "Rectify a level change under the influence of `org-odd-levels-only'
  7193. LEVEL is a current level, CHANGE is by how much the level should be
  7194. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7195. even level numbers will become the next higher odd number."
  7196. (if org-odd-levels-only
  7197. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7198. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7199. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7200. (max 1 (+ level (or change 0)))))
  7201. (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
  7202. (defun org-promote ()
  7203. "Promote the current heading higher up the tree."
  7204. (org-with-wide-buffer
  7205. (org-back-to-heading t)
  7206. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7207. after-change-functions))
  7208. (level (save-match-data (funcall outline-level)))
  7209. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7210. (diff (abs (- level (length up-head) -1))))
  7211. (cond
  7212. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7213. (replace-match "# " nil t))
  7214. ((= level 1)
  7215. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7216. (t (replace-match up-head nil t)))
  7217. (unless (= level 1)
  7218. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7219. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7220. (run-hooks 'org-after-promote-entry-hook))))
  7221. (defun org-demote ()
  7222. "Demote the current heading lower down the tree."
  7223. (org-with-wide-buffer
  7224. (org-back-to-heading t)
  7225. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7226. after-change-functions))
  7227. (level (save-match-data (funcall outline-level)))
  7228. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7229. (diff (abs (- level (length down-head) -1))))
  7230. (replace-match down-head nil t)
  7231. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7232. (when org-adapt-indentation (org-fixup-indentation diff))
  7233. (run-hooks 'org-after-demote-entry-hook))))
  7234. (defun org-cycle-level ()
  7235. "Cycle the level of an empty headline through possible states.
  7236. This goes first to child, then to parent, level, then up the hierarchy.
  7237. After top level, it switches back to sibling level."
  7238. (interactive)
  7239. (let ((org-adapt-indentation nil))
  7240. (when (org-point-at-end-of-empty-headline)
  7241. (setq this-command 'org-cycle-level) ; Only needed for caching
  7242. (let ((cur-level (org-current-level))
  7243. (prev-level (org-get-previous-line-level)))
  7244. (cond
  7245. ;; If first headline in file, promote to top-level.
  7246. ((= prev-level 0)
  7247. (loop repeat (/ (- cur-level 1) (org-level-increment))
  7248. do (org-do-promote)))
  7249. ;; If same level as prev, demote one.
  7250. ((= prev-level cur-level)
  7251. (org-do-demote))
  7252. ;; If parent is top-level, promote to top level if not already.
  7253. ((= prev-level 1)
  7254. (loop repeat (/ (- cur-level 1) (org-level-increment))
  7255. do (org-do-promote)))
  7256. ;; If top-level, return to prev-level.
  7257. ((= cur-level 1)
  7258. (loop repeat (/ (- prev-level 1) (org-level-increment))
  7259. do (org-do-demote)))
  7260. ;; If less than prev-level, promote one.
  7261. ((< cur-level prev-level)
  7262. (org-do-promote))
  7263. ;; If deeper than prev-level, promote until higher than
  7264. ;; prev-level.
  7265. ((> cur-level prev-level)
  7266. (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7267. do (org-do-promote))))
  7268. t))))
  7269. (defun org-map-tree (fun)
  7270. "Call FUN for every heading underneath the current one."
  7271. (org-back-to-heading)
  7272. (let ((level (funcall outline-level)))
  7273. (save-excursion
  7274. (funcall fun)
  7275. (while (and (progn
  7276. (outline-next-heading)
  7277. (> (funcall outline-level) level))
  7278. (not (eobp)))
  7279. (funcall fun)))))
  7280. (defun org-map-region (fun beg end)
  7281. "Call FUN for every heading between BEG and END."
  7282. (let ((org-ignore-region t))
  7283. (save-excursion
  7284. (setq end (copy-marker end))
  7285. (goto-char beg)
  7286. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7287. (< (point) end))
  7288. (funcall fun))
  7289. (while (and (progn
  7290. (outline-next-heading)
  7291. (< (point) end))
  7292. (not (eobp)))
  7293. (funcall fun)))))
  7294. (defun org-fixup-indentation (diff)
  7295. "Change the indentation in the current entry by DIFF.
  7296. DIFF is an integer. Indentation is done according to the
  7297. following rules:
  7298. - Planning information and property drawers are always indented
  7299. according to the new level of the headline;
  7300. - Footnote definitions and their contents are ignored;
  7301. - Inlinetasks' boundaries are not shifted;
  7302. - Empty lines are ignored;
  7303. - Other lines' indentation are shifted by DIFF columns, unless
  7304. it would introduce a structural change in the document, in
  7305. which case no shifting is done at all.
  7306. Assume point is at a heading or an inlinetask beginning."
  7307. (org-with-wide-buffer
  7308. (narrow-to-region (line-beginning-position)
  7309. (save-excursion
  7310. (if (org-with-limited-levels (org-at-heading-p))
  7311. (org-with-limited-levels (outline-next-heading))
  7312. (org-inlinetask-goto-end))
  7313. (point)))
  7314. (forward-line)
  7315. ;; Indent properly planning info and property drawer.
  7316. (when (org-looking-at-p org-planning-line-re)
  7317. (org-indent-line)
  7318. (forward-line))
  7319. (when (looking-at org-property-drawer-re)
  7320. (goto-char (match-end 0))
  7321. (forward-line)
  7322. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7323. (catch 'no-shift
  7324. (when (zerop diff) (throw 'no-shift nil))
  7325. ;; If DIFF is negative, first check if a shift is possible at all
  7326. ;; (e.g., it doesn't break structure). This can only happen if
  7327. ;; some contents are not properly indented.
  7328. (let ((case-fold-search t))
  7329. (when (< diff 0)
  7330. (let ((diff (- diff))
  7331. (forbidden-re (concat org-outline-regexp
  7332. "\\|"
  7333. (substring org-footnote-definition-re 1))))
  7334. (save-excursion
  7335. (while (not (eobp))
  7336. (cond
  7337. ((org-looking-at-p "[ \t]*$") (forward-line))
  7338. ((and (org-looking-at-p org-footnote-definition-re)
  7339. (let ((e (org-element-at-point)))
  7340. (and (eq (org-element-type e) 'footnote-definition)
  7341. (goto-char (org-element-property :end e))))))
  7342. ((org-looking-at-p org-outline-regexp) (forward-line))
  7343. ;; Give up if shifting would move before column 0 or
  7344. ;; if it would introduce a headline or a footnote
  7345. ;; definition.
  7346. (t
  7347. (skip-chars-forward " \t")
  7348. (let ((ind (current-column)))
  7349. (when (or (< ind diff)
  7350. (and (= ind diff) (org-looking-at-p forbidden-re)))
  7351. (throw 'no-shift nil)))
  7352. ;; Ignore contents of example blocks and source
  7353. ;; blocks if their indentation is meant to be
  7354. ;; preserved. Jump to block's closing line.
  7355. (beginning-of-line)
  7356. (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7357. (let ((e (org-element-at-point)))
  7358. (and (memq (org-element-type e)
  7359. '(example-block src-block))
  7360. (or org-src-preserve-indentation
  7361. (org-element-property :preserve-indent e))
  7362. (goto-char (org-element-property :end e))
  7363. (progn (skip-chars-backward " \r\t\n")
  7364. (beginning-of-line)
  7365. t))))
  7366. (forward-line))))))))
  7367. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7368. ;; by DIFF. Also skip contents of source or example blocks
  7369. ;; when indentation is meant to be preserved.
  7370. (while (not (eobp))
  7371. (cond
  7372. ((and (org-looking-at-p org-footnote-definition-re)
  7373. (let ((e (org-element-at-point)))
  7374. (and (eq (org-element-type e) 'footnote-definition)
  7375. (goto-char (org-element-property :end e))))))
  7376. ((org-looking-at-p org-outline-regexp) (forward-line))
  7377. ((org-looking-at-p "[ \t]*$") (forward-line))
  7378. (t
  7379. (org-indent-line-to (+ (org-get-indentation) diff))
  7380. (beginning-of-line)
  7381. (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7382. (let ((e (org-element-at-point)))
  7383. (and (memq (org-element-type e)
  7384. '(example-block src-block))
  7385. (or org-src-preserve-indentation
  7386. (org-element-property :preserve-indent e))
  7387. (goto-char (org-element-property :end e))
  7388. (progn (skip-chars-backward " \r\t\n")
  7389. (beginning-of-line)
  7390. t))))
  7391. (forward-line)))))))))
  7392. (defun org-convert-to-odd-levels ()
  7393. "Convert an org-mode file with all levels allowed to one with odd levels.
  7394. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7395. level 5 etc."
  7396. (interactive)
  7397. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7398. (let ((outline-level 'org-outline-level)
  7399. (org-odd-levels-only nil) n)
  7400. (save-excursion
  7401. (goto-char (point-min))
  7402. (while (re-search-forward "^\\*\\*+ " nil t)
  7403. (setq n (- (length (match-string 0)) 2))
  7404. (while (>= (setq n (1- n)) 0)
  7405. (org-demote))
  7406. (end-of-line 1))))))
  7407. (defun org-convert-to-oddeven-levels ()
  7408. "Convert an org-mode file with only odd levels to one with odd/even levels.
  7409. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7410. file contains a section with an even level, conversion would
  7411. destroy the structure of the file. An error is signaled in this
  7412. case."
  7413. (interactive)
  7414. (goto-char (point-min))
  7415. ;; First check if there are no even levels
  7416. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7417. (org-show-set-visibility 'canonical)
  7418. (error "Not all levels are odd in this file. Conversion not possible"))
  7419. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7420. (let ((outline-regexp org-outline-regexp)
  7421. (outline-level 'org-outline-level)
  7422. (org-odd-levels-only nil) n)
  7423. (save-excursion
  7424. (goto-char (point-min))
  7425. (while (re-search-forward "^\\*\\*+ " nil t)
  7426. (setq n (/ (1- (length (match-string 0))) 2))
  7427. (while (>= (setq n (1- n)) 0)
  7428. (org-promote))
  7429. (end-of-line 1))))))
  7430. (defun org-tr-level (n)
  7431. "Make N odd if required."
  7432. (if org-odd-levels-only (1+ (/ n 2)) n))
  7433. ;;; Vertical tree motion, cutting and pasting of subtrees
  7434. (defun org-move-subtree-up (&optional arg)
  7435. "Move the current subtree up past ARG headlines of the same level."
  7436. (interactive "p")
  7437. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7438. (defun org-move-subtree-down (&optional arg)
  7439. "Move the current subtree down past ARG headlines of the same level."
  7440. (interactive "p")
  7441. (setq arg (prefix-numeric-value arg))
  7442. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7443. 'org-get-last-sibling))
  7444. (ins-point (make-marker))
  7445. (cnt (abs arg))
  7446. (col (current-column))
  7447. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7448. ;; Select the tree
  7449. (org-back-to-heading)
  7450. (setq beg0 (point))
  7451. (save-excursion
  7452. (setq ne-beg (org-back-over-empty-lines))
  7453. (setq beg (point)))
  7454. (save-match-data
  7455. (save-excursion (outline-end-of-heading)
  7456. (setq folded (outline-invisible-p)))
  7457. (progn (org-end-of-subtree nil t)
  7458. (unless (eobp) (backward-char))))
  7459. (outline-next-heading)
  7460. (setq ne-end (org-back-over-empty-lines))
  7461. (setq end (point))
  7462. (goto-char beg0)
  7463. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7464. ;; include less whitespace
  7465. (save-excursion
  7466. (goto-char beg)
  7467. (forward-line (- ne-beg ne-end))
  7468. (setq beg (point))))
  7469. ;; Find insertion point, with error handling
  7470. (while (> cnt 0)
  7471. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7472. (progn (goto-char beg0)
  7473. (user-error "Cannot move past superior level or buffer limit")))
  7474. (setq cnt (1- cnt)))
  7475. (when (> arg 0)
  7476. ;; Moving forward - still need to move over subtree
  7477. (org-end-of-subtree t t)
  7478. (save-excursion
  7479. (org-back-over-empty-lines)
  7480. (or (bolp) (newline))))
  7481. (setq ne-ins (org-back-over-empty-lines))
  7482. (move-marker ins-point (point))
  7483. (setq txt (buffer-substring beg end))
  7484. (org-save-markers-in-region beg end)
  7485. (delete-region beg end)
  7486. (org-remove-empty-overlays-at beg)
  7487. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7488. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7489. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7490. (let ((bbb (point)))
  7491. (insert-before-markers txt)
  7492. (org-reinstall-markers-in-region bbb)
  7493. (move-marker ins-point bbb))
  7494. (or (bolp) (insert "\n"))
  7495. (setq ins-end (point))
  7496. (goto-char ins-point)
  7497. (org-skip-whitespace)
  7498. (when (and (< arg 0)
  7499. (org-first-sibling-p)
  7500. (> ne-ins ne-beg))
  7501. ;; Move whitespace back to beginning
  7502. (save-excursion
  7503. (goto-char ins-end)
  7504. (let ((kill-whole-line t))
  7505. (kill-line (- ne-ins ne-beg)) (point)))
  7506. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7507. (move-marker ins-point nil)
  7508. (if folded
  7509. (outline-hide-subtree)
  7510. (org-show-entry)
  7511. (org-show-children)
  7512. (org-cycle-hide-drawers 'children))
  7513. (org-clean-visibility-after-subtree-move)
  7514. ;; move back to the initial column we were at
  7515. (move-to-column col)))
  7516. (defvar org-subtree-clip ""
  7517. "Clipboard for cut and paste of subtrees.
  7518. This is actually only a copy of the kill, because we use the normal kill
  7519. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7520. (defvar org-subtree-clip-folded nil
  7521. "Was the last copied subtree folded?
  7522. This is used to fold the tree back after pasting.")
  7523. (defun org-cut-subtree (&optional n)
  7524. "Cut the current subtree into the clipboard.
  7525. With prefix arg N, cut this many sequential subtrees.
  7526. This is a short-hand for marking the subtree and then cutting it."
  7527. (interactive "p")
  7528. (org-copy-subtree n 'cut))
  7529. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7530. "Copy the current subtree it in the clipboard.
  7531. With prefix arg N, copy this many sequential subtrees.
  7532. This is a short-hand for marking the subtree and then copying it.
  7533. If CUT is non-nil, actually cut the subtree.
  7534. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7535. of some markers in the region, even if CUT is non-nil. This is
  7536. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7537. (interactive "p")
  7538. (let (beg end folded (beg0 (point)))
  7539. (if (org-called-interactively-p 'any)
  7540. (org-back-to-heading nil) ; take what looks like a subtree
  7541. (org-back-to-heading t)) ; take what is really there
  7542. (setq beg (point))
  7543. (skip-chars-forward " \t\r\n")
  7544. (save-match-data
  7545. (if nosubtrees
  7546. (outline-next-heading)
  7547. (save-excursion (outline-end-of-heading)
  7548. (setq folded (outline-invisible-p)))
  7549. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7550. (org-end-of-subtree t t)))
  7551. ;; Include the end of an inlinetask
  7552. (when (and (featurep 'org-inlinetask)
  7553. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7554. "END[ \t]*$")))
  7555. (end-of-line))
  7556. (setq end (point))
  7557. (goto-char beg0)
  7558. (when (> end beg)
  7559. (setq org-subtree-clip-folded folded)
  7560. (when (or cut force-store-markers)
  7561. (org-save-markers-in-region beg end))
  7562. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7563. (setq org-subtree-clip (current-kill 0))
  7564. (message "%s: Subtree(s) with %d characters"
  7565. (if cut "Cut" "Copied")
  7566. (length org-subtree-clip)))))
  7567. (defun org-paste-subtree (&optional level tree for-yank remove)
  7568. "Paste the clipboard as a subtree, with modification of headline level.
  7569. The entire subtree is promoted or demoted in order to match a new headline
  7570. level.
  7571. If the cursor is at the beginning of a headline, the same level as
  7572. that headline is used to paste the tree.
  7573. If not, the new level is derived from the *visible* headings
  7574. before and after the insertion point, and taken to be the inferior headline
  7575. level of the two. So if the previous visible heading is level 3 and the
  7576. next is level 4 (or vice versa), level 4 will be used for insertion.
  7577. This makes sure that the subtree remains an independent subtree and does
  7578. not swallow low level entries.
  7579. You can also force a different level, either by using a numeric prefix
  7580. argument, or by inserting the heading marker by hand. For example, if the
  7581. cursor is after \"*****\", then the tree will be shifted to level 5.
  7582. If optional TREE is given, use this text instead of the kill ring.
  7583. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7584. move back over whitespace before inserting, and move point to the end of
  7585. the inserted text when done.
  7586. When REMOVE is non-nil, remove the subtree from the clipboard."
  7587. (interactive "P")
  7588. (setq tree (or tree (and kill-ring (current-kill 0))))
  7589. (unless (org-kill-is-subtree-p tree)
  7590. (user-error "%s"
  7591. (substitute-command-keys
  7592. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7593. (org-with-limited-levels
  7594. (let* ((visp (not (outline-invisible-p)))
  7595. (txt tree)
  7596. (^re_ "\\(\\*+\\)[ \t]*")
  7597. (old-level (if (string-match org-outline-regexp-bol txt)
  7598. (- (match-end 0) (match-beginning 0) 1)
  7599. -1))
  7600. (force-level (cond (level (prefix-numeric-value level))
  7601. ((and (looking-at "[ \t]*$")
  7602. (string-match
  7603. "^\\*+$" (buffer-substring
  7604. (point-at-bol) (point))))
  7605. (- (match-end 0) (match-beginning 0)))
  7606. ((and (bolp)
  7607. (looking-at org-outline-regexp))
  7608. (- (match-end 0) (point) 1))))
  7609. (previous-level (save-excursion
  7610. (condition-case nil
  7611. (progn
  7612. (outline-previous-visible-heading 1)
  7613. (if (looking-at ^re_)
  7614. (- (match-end 0) (match-beginning 0) 1)
  7615. 1))
  7616. (error 1))))
  7617. (next-level (save-excursion
  7618. (condition-case nil
  7619. (progn
  7620. (or (looking-at org-outline-regexp)
  7621. (outline-next-visible-heading 1))
  7622. (if (looking-at ^re_)
  7623. (- (match-end 0) (match-beginning 0) 1)
  7624. 1))
  7625. (error 1))))
  7626. (new-level (or force-level (max previous-level next-level)))
  7627. (shift (if (or (= old-level -1)
  7628. (= new-level -1)
  7629. (= old-level new-level))
  7630. 0
  7631. (- new-level old-level)))
  7632. (delta (if (> shift 0) -1 1))
  7633. (func (if (> shift 0) 'org-demote 'org-promote))
  7634. (org-odd-levels-only nil)
  7635. beg end newend)
  7636. ;; Remove the forced level indicator
  7637. (when force-level
  7638. (delete-region (point-at-bol) (point)))
  7639. ;; Paste
  7640. (beginning-of-line (if (bolp) 1 2))
  7641. (setq beg (point))
  7642. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7643. (insert-before-markers txt)
  7644. (unless (string-match "\n\\'" txt) (insert "\n"))
  7645. (setq newend (point))
  7646. (org-reinstall-markers-in-region beg)
  7647. (setq end (point))
  7648. (goto-char beg)
  7649. (skip-chars-forward " \t\n\r")
  7650. (setq beg (point))
  7651. (when (and (outline-invisible-p) visp)
  7652. (save-excursion (outline-show-heading)))
  7653. ;; Shift if necessary
  7654. (unless (= shift 0)
  7655. (save-restriction
  7656. (narrow-to-region beg end)
  7657. (while (not (= shift 0))
  7658. (org-map-region func (point-min) (point-max))
  7659. (setq shift (+ delta shift)))
  7660. (goto-char (point-min))
  7661. (setq newend (point-max))))
  7662. (when (or (org-called-interactively-p 'interactive) for-yank)
  7663. (message "Clipboard pasted as level %d subtree" new-level))
  7664. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7665. kill-ring
  7666. (eq org-subtree-clip (current-kill 0))
  7667. org-subtree-clip-folded)
  7668. ;; The tree was folded before it was killed/copied
  7669. (outline-hide-subtree))
  7670. (and for-yank (goto-char newend))
  7671. (and remove (setq kill-ring (cdr kill-ring))))))
  7672. (defun org-kill-is-subtree-p (&optional txt)
  7673. "Check if the current kill is an outline subtree, or a set of trees.
  7674. Returns nil if kill does not start with a headline, or if the first
  7675. headline level is not the largest headline level in the tree.
  7676. So this will actually accept several entries of equal levels as well,
  7677. which is OK for `org-paste-subtree'.
  7678. If optional TXT is given, check this string instead of the current kill."
  7679. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7680. (re (org-get-limited-outline-regexp))
  7681. (^re (concat "^" re))
  7682. (start-level (and kill
  7683. (string-match
  7684. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7685. kill)
  7686. (- (match-end 2) (match-beginning 2) 1)))
  7687. (start (1+ (or (match-beginning 2) -1))))
  7688. (if (not start-level)
  7689. (progn
  7690. nil) ;; does not even start with a heading
  7691. (catch 'exit
  7692. (while (setq start (string-match ^re kill (1+ start)))
  7693. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7694. (throw 'exit nil)))
  7695. t))))
  7696. (defvar org-markers-to-move nil
  7697. "Markers that should be moved with a cut-and-paste operation.
  7698. Those markers are stored together with their positions relative to
  7699. the start of the region.")
  7700. (defun org-save-markers-in-region (beg end)
  7701. "Check markers in region.
  7702. If these markers are between BEG and END, record their position relative
  7703. to BEG, so that after moving the block of text, we can put the markers back
  7704. into place.
  7705. This function gets called just before an entry or tree gets cut from the
  7706. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7707. called immediately, to move the markers with the entries."
  7708. (setq org-markers-to-move nil)
  7709. (when (featurep 'org-clock)
  7710. (org-clock-save-markers-for-cut-and-paste beg end))
  7711. (when (featurep 'org-agenda)
  7712. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7713. (defun org-check-and-save-marker (marker beg end)
  7714. "Check if MARKER is between BEG and END.
  7715. If yes, remember the marker and the distance to BEG."
  7716. (when (and (marker-buffer marker)
  7717. (equal (marker-buffer marker) (current-buffer))
  7718. (>= marker beg) (< marker end))
  7719. (push (cons marker (- marker beg)) org-markers-to-move)))
  7720. (defun org-reinstall-markers-in-region (beg)
  7721. "Move all remembered markers to their position relative to BEG."
  7722. (mapc (lambda (x)
  7723. (move-marker (car x) (+ beg (cdr x))))
  7724. org-markers-to-move)
  7725. (setq org-markers-to-move nil))
  7726. (defun org-narrow-to-subtree ()
  7727. "Narrow buffer to the current subtree."
  7728. (interactive)
  7729. (save-excursion
  7730. (save-match-data
  7731. (org-with-limited-levels
  7732. (narrow-to-region
  7733. (progn (org-back-to-heading t) (point))
  7734. (progn (org-end-of-subtree t t)
  7735. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7736. (point)))))))
  7737. (defun org-narrow-to-block ()
  7738. "Narrow buffer to the current block."
  7739. (interactive)
  7740. (let* ((case-fold-search t)
  7741. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7742. "^[ \t]*#\\+end_.*")))
  7743. (if blockp
  7744. (narrow-to-region (car blockp) (cdr blockp))
  7745. (user-error "Not in a block"))))
  7746. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7747. "Clone the task (subtree) at point N times.
  7748. The clones will be inserted as siblings.
  7749. In interactive use, the user will be prompted for the number of
  7750. clones to be produced. If the entry has a timestamp, the user
  7751. will also be prompted for a time shift, which may be a repeater
  7752. as used in time stamps, for example `+3d'. To disable this,
  7753. you can call the function with a universal prefix argument.
  7754. When a valid repeater is given and the entry contains any time
  7755. stamps, the clones will become a sequence in time, with time
  7756. stamps in the subtree shifted for each clone produced. If SHIFT
  7757. is nil or the empty string, time stamps will be left alone. The
  7758. ID property of the original subtree is removed.
  7759. If the original subtree did contain time stamps with a repeater,
  7760. the following will happen:
  7761. - the repeater will be removed in each clone
  7762. - an additional clone will be produced, with the current, unshifted
  7763. date(s) in the entry.
  7764. - the original entry will be placed *after* all the clones, with
  7765. repeater intact.
  7766. - the start days in the repeater in the original entry will be shifted
  7767. to past the last clone.
  7768. In this way you can spell out a number of instances of a repeating task,
  7769. and still retain the repeater to cover future instances of the task.
  7770. As described above, N+1 clones are produced when the original
  7771. subtree has a repeater. Setting N to 0, then, can be used to
  7772. remove the repeater from a subtree and create a shifted clone
  7773. with the original repeater."
  7774. (interactive "nNumber of clones to produce: ")
  7775. (let ((shift
  7776. (or shift
  7777. (if (and (not (equal current-prefix-arg '(4)))
  7778. (save-excursion
  7779. (re-search-forward org-ts-regexp-both
  7780. (save-excursion
  7781. (org-end-of-subtree t)
  7782. (point)) t)))
  7783. (read-from-minibuffer
  7784. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7785. ""))) ;; No time shift
  7786. (n-no-remove -1)
  7787. (drawer-re org-drawer-regexp)
  7788. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7789. beg end template task idprop
  7790. shift-n shift-what doshift nmin nmax)
  7791. (unless (wholenump n)
  7792. (user-error "Invalid number of replications %s" n))
  7793. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7794. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7795. shift)))
  7796. (user-error "Invalid shift specification %s" shift))
  7797. (when doshift
  7798. (setq shift-n (string-to-number (match-string 1 shift))
  7799. shift-what (cdr (assoc (match-string 2 shift)
  7800. '(("d" . day) ("w" . week)
  7801. ("m" . month) ("y" . year))))))
  7802. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  7803. (setq nmin 1 nmax n)
  7804. (org-back-to-heading t)
  7805. (setq beg (point))
  7806. (setq idprop (org-entry-get nil "ID"))
  7807. (org-end-of-subtree t t)
  7808. (or (bolp) (insert "\n"))
  7809. (setq end (point))
  7810. (setq template (buffer-substring beg end))
  7811. (when (and doshift
  7812. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  7813. (delete-region beg end)
  7814. (setq end beg)
  7815. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  7816. (goto-char end)
  7817. (loop for n from nmin to nmax do
  7818. ;; prepare clone
  7819. (with-temp-buffer
  7820. (insert template)
  7821. (org-mode)
  7822. (goto-char (point-min))
  7823. (org-show-subtree)
  7824. (and idprop (if org-clone-delete-id
  7825. (org-entry-delete nil "ID")
  7826. (org-id-get-create t)))
  7827. (unless (= n 0)
  7828. (while (re-search-forward org-clock-re nil t)
  7829. (kill-whole-line))
  7830. (goto-char (point-min))
  7831. (while (re-search-forward drawer-re nil t)
  7832. (org-remove-empty-drawer-at (point))))
  7833. (goto-char (point-min))
  7834. (when doshift
  7835. (while (re-search-forward org-ts-regexp-both nil t)
  7836. (org-timestamp-change (* n shift-n) shift-what))
  7837. (unless (= n n-no-remove)
  7838. (goto-char (point-min))
  7839. (while (re-search-forward org-ts-regexp nil t)
  7840. (save-excursion
  7841. (goto-char (match-beginning 0))
  7842. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7843. (delete-region (match-beginning 1) (match-end 1)))))))
  7844. (setq task (buffer-string)))
  7845. (insert task))
  7846. (goto-char beg)))
  7847. ;;; Outline Sorting
  7848. (defun org-sort (with-case)
  7849. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7850. Optional argument WITH-CASE means sort case-sensitively."
  7851. (interactive "P")
  7852. (cond
  7853. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  7854. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  7855. (t
  7856. (org-call-with-arg 'org-sort-entries with-case))))
  7857. (defun org-sort-remove-invisible (s)
  7858. "Remove invisible links from string S."
  7859. (remove-text-properties 0 (length s) org-rm-props s)
  7860. (while (string-match org-bracket-link-regexp s)
  7861. (setq s (replace-match (if (match-end 2)
  7862. (match-string 3 s)
  7863. (match-string 1 s))
  7864. t t s)))
  7865. (let ((st (format " %s " s)))
  7866. (while (string-match org-emph-re st)
  7867. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  7868. (setq s (substring st 1 -1)))
  7869. s)
  7870. (defvar org-priority-regexp) ; defined later in the file
  7871. (defvar org-after-sorting-entries-or-items-hook nil
  7872. "Hook that is run after a bunch of entries or items have been sorted.
  7873. When children are sorted, the cursor is in the parent line when this
  7874. hook gets called. When a region or a plain list is sorted, the cursor
  7875. will be in the first entry of the sorted region/list.")
  7876. (defun org-sort-entries
  7877. (&optional with-case sorting-type getkey-func compare-func property)
  7878. "Sort entries on a certain level of an outline tree.
  7879. If there is an active region, the entries in the region are sorted.
  7880. Else, if the cursor is before the first entry, sort the top-level items.
  7881. Else, the children of the entry at point are sorted.
  7882. Sorting can be alphabetically, numerically, by date/time as given by
  7883. a time stamp, by a property, by priority order, or by a custom function.
  7884. The command prompts for the sorting type unless it has been given to the
  7885. function through the SORTING-TYPE argument, which needs to be a character,
  7886. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7887. the precise meaning of each character:
  7888. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7889. c By creation time, which is assumed to be the first inactive time stamp
  7890. at the beginning of a line.
  7891. d By deadline date/time.
  7892. k By clocking time.
  7893. n Numerically, by converting the beginning of the entry/item to a number.
  7894. o By order of TODO keywords.
  7895. p By priority according to the cookie.
  7896. r By the value of a property.
  7897. s By scheduled date/time.
  7898. t By date/time, either the first active time stamp in the entry, or, if
  7899. none exist, by the first inactive one.
  7900. Capital letters will reverse the sort order.
  7901. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7902. called with point at the beginning of the record. It must return either
  7903. a string or a number that should serve as the sorting key for that record.
  7904. Comparing entries ignores case by default. However, with an optional argument
  7905. WITH-CASE, the sorting considers case as well.
  7906. Sorting is done against the visible part of the headlines, it ignores hidden
  7907. links.
  7908. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  7909. (interactive "P")
  7910. (let ((case-func (if with-case 'identity 'downcase))
  7911. (cmstr
  7912. ;; The clock marker is lost when using `sort-subr', let's
  7913. ;; store the clocking string.
  7914. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  7915. (save-excursion
  7916. (goto-char org-clock-marker)
  7917. (buffer-substring-no-properties (line-beginning-position)
  7918. (point)))))
  7919. start beg end stars re re2
  7920. txt what tmp)
  7921. ;; Find beginning and end of region to sort
  7922. (cond
  7923. ((org-region-active-p)
  7924. ;; we will sort the region
  7925. (setq end (region-end)
  7926. what "region")
  7927. (goto-char (region-beginning))
  7928. (unless (org-at-heading-p) (outline-next-heading))
  7929. (setq start (point)))
  7930. ((or (org-at-heading-p)
  7931. (ignore-errors (progn (org-back-to-heading) t)))
  7932. ;; we will sort the children of the current headline
  7933. (org-back-to-heading)
  7934. (setq start (point)
  7935. end (progn (org-end-of-subtree t t)
  7936. (or (bolp) (insert "\n"))
  7937. (when (>= (org-back-over-empty-lines) 1)
  7938. (forward-line 1))
  7939. (point))
  7940. what "children")
  7941. (goto-char start)
  7942. (outline-show-subtree)
  7943. (outline-next-heading))
  7944. (t
  7945. ;; we will sort the top-level entries in this file
  7946. (goto-char (point-min))
  7947. (or (org-at-heading-p) (outline-next-heading))
  7948. (setq start (point))
  7949. (goto-char (point-max))
  7950. (beginning-of-line 1)
  7951. (when (looking-at ".*?\\S-")
  7952. ;; File ends in a non-white line
  7953. (end-of-line 1)
  7954. (insert "\n"))
  7955. (setq end (point-max))
  7956. (setq what "top-level")
  7957. (goto-char start)
  7958. (outline-show-all)))
  7959. (setq beg (point))
  7960. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7961. (looking-at "\\(\\*+\\)")
  7962. (setq stars (match-string 1)
  7963. re (concat "^" (regexp-quote stars) " +")
  7964. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7965. txt (buffer-substring beg end))
  7966. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7967. (when (and (not (equal stars "*")) (string-match re2 txt))
  7968. (user-error "Region to sort contains a level above the first entry"))
  7969. (unless sorting-type
  7970. (message
  7971. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7972. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7973. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7974. what)
  7975. (setq sorting-type (read-char-exclusive))
  7976. (unless getkey-func
  7977. (and (= (downcase sorting-type) ?f)
  7978. (setq getkey-func
  7979. (completing-read "Sort using function: "
  7980. obarray 'fboundp t nil nil))
  7981. (setq getkey-func (intern getkey-func))))
  7982. (and (= (downcase sorting-type) ?r)
  7983. (not property)
  7984. (setq property
  7985. (completing-read "Property: "
  7986. (mapcar #'list (org-buffer-property-keys t))
  7987. nil t))))
  7988. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7989. (message "Sorting entries...")
  7990. (save-restriction
  7991. (narrow-to-region start end)
  7992. (let ((dcst (downcase sorting-type))
  7993. (case-fold-search nil)
  7994. (now (current-time)))
  7995. (sort-subr
  7996. (/= dcst sorting-type)
  7997. ;; This function moves to the beginning character of the "record" to
  7998. ;; be sorted.
  7999. (lambda nil
  8000. (if (re-search-forward re nil t)
  8001. (goto-char (match-beginning 0))
  8002. (goto-char (point-max))))
  8003. ;; This function moves to the last character of the "record" being
  8004. ;; sorted.
  8005. (lambda nil
  8006. (save-match-data
  8007. (condition-case nil
  8008. (outline-forward-same-level 1)
  8009. (error
  8010. (goto-char (point-max))))))
  8011. ;; This function returns the value that gets sorted against.
  8012. (lambda nil
  8013. (cond
  8014. ((= dcst ?n)
  8015. (if (looking-at org-complex-heading-regexp)
  8016. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8017. nil))
  8018. ((= dcst ?a)
  8019. (if (looking-at org-complex-heading-regexp)
  8020. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8021. nil))
  8022. ((= dcst ?k)
  8023. (or (get-text-property (point) :org-clock-minutes) 0))
  8024. ((= dcst ?t)
  8025. (let ((end (save-excursion (outline-next-heading) (point))))
  8026. (if (or (re-search-forward org-ts-regexp end t)
  8027. (re-search-forward org-ts-regexp-both end t))
  8028. (org-time-string-to-seconds (match-string 0))
  8029. (org-float-time now))))
  8030. ((= dcst ?c)
  8031. (let ((end (save-excursion (outline-next-heading) (point))))
  8032. (if (re-search-forward
  8033. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8034. end t)
  8035. (org-time-string-to-seconds (match-string 0))
  8036. (org-float-time now))))
  8037. ((= dcst ?s)
  8038. (let ((end (save-excursion (outline-next-heading) (point))))
  8039. (if (re-search-forward org-scheduled-time-regexp end t)
  8040. (org-time-string-to-seconds (match-string 1))
  8041. (org-float-time now))))
  8042. ((= dcst ?d)
  8043. (let ((end (save-excursion (outline-next-heading) (point))))
  8044. (if (re-search-forward org-deadline-time-regexp end t)
  8045. (org-time-string-to-seconds (match-string 1))
  8046. (org-float-time now))))
  8047. ((= dcst ?p)
  8048. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8049. (string-to-char (match-string 2))
  8050. org-default-priority))
  8051. ((= dcst ?r)
  8052. (or (org-entry-get nil property) ""))
  8053. ((= dcst ?o)
  8054. (when (looking-at org-complex-heading-regexp)
  8055. (let* ((m (match-string 2))
  8056. (s (if (member m org-done-keywords) '- '+)))
  8057. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8058. ((= dcst ?f)
  8059. (if getkey-func
  8060. (progn
  8061. (setq tmp (funcall getkey-func))
  8062. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8063. tmp)
  8064. (error "Invalid key function `%s'" getkey-func)))
  8065. (t (error "Invalid sorting type `%c'" sorting-type))))
  8066. nil
  8067. (cond
  8068. ((= dcst ?a) 'string<)
  8069. ((= dcst ?f) compare-func)
  8070. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8071. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8072. ;; Reset the clock marker if needed
  8073. (when cmstr
  8074. (save-excursion
  8075. (goto-char start)
  8076. (search-forward cmstr nil t)
  8077. (move-marker org-clock-marker (point))))
  8078. (message "Sorting entries...done")))
  8079. ;;; The orgstruct minor mode
  8080. ;; Define a minor mode which can be used in other modes in order to
  8081. ;; integrate the org-mode structure editing commands.
  8082. ;; This is really a hack, because the org-mode structure commands use
  8083. ;; keys which normally belong to the major mode. Here is how it
  8084. ;; works: The minor mode defines all the keys necessary to operate the
  8085. ;; structure commands, but wraps the commands into a function which
  8086. ;; tests if the cursor is currently at a headline or a plain list
  8087. ;; item. If that is the case, the structure command is used,
  8088. ;; temporarily setting many Org-mode variables like regular
  8089. ;; expressions for filling etc. However, when any of those keys is
  8090. ;; used at a different location, function uses `key-binding' to look
  8091. ;; up if the key has an associated command in another currently active
  8092. ;; keymap (minor modes, major mode, global), and executes that
  8093. ;; command. There might be problems if any of the keys is otherwise
  8094. ;; used as a prefix key.
  8095. (defcustom orgstruct-heading-prefix-regexp ""
  8096. "Regexp that matches the custom prefix of Org headlines in
  8097. orgstruct(++)-mode."
  8098. :group 'org
  8099. :version "24.4"
  8100. :package-version '(Org . "8.3")
  8101. :type 'regexp)
  8102. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8103. (defcustom orgstruct-setup-hook nil
  8104. "Hook run after orgstruct-mode-map is filled."
  8105. :group 'org
  8106. :version "24.4"
  8107. :package-version '(Org . "8.0")
  8108. :type 'hook)
  8109. (defvar orgstruct-initialized nil)
  8110. (defvar org-local-vars nil
  8111. "List of local variables, for use by `orgstruct-mode'.")
  8112. ;;;###autoload
  8113. (define-minor-mode orgstruct-mode
  8114. "Toggle the minor mode `orgstruct-mode'.
  8115. This mode is for using Org-mode structure commands in other
  8116. modes. The following keys behave as if Org-mode were active, if
  8117. the cursor is on a headline, or on a plain list item (both as
  8118. defined by Org-mode)."
  8119. nil " OrgStruct" (make-sparse-keymap)
  8120. (funcall (if orgstruct-mode
  8121. 'add-to-invisibility-spec
  8122. 'remove-from-invisibility-spec)
  8123. '(outline . t))
  8124. (when orgstruct-mode
  8125. (org-load-modules-maybe)
  8126. (unless orgstruct-initialized
  8127. (orgstruct-setup)
  8128. (setq orgstruct-initialized t))))
  8129. ;;;###autoload
  8130. (defun turn-on-orgstruct ()
  8131. "Unconditionally turn on `orgstruct-mode'."
  8132. (orgstruct-mode 1))
  8133. (defvar-local orgstruct-is-++ nil
  8134. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8135. (defvar-local org-fb-vars nil)
  8136. (defun orgstruct++-mode (&optional arg)
  8137. "Toggle `orgstruct-mode', the enhanced version of it.
  8138. In addition to setting orgstruct-mode, this also exports all
  8139. indentation and autofilling variables from org-mode into the
  8140. buffer. It will also recognize item context in multiline items."
  8141. (interactive "P")
  8142. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8143. (if (< arg 1)
  8144. (progn (orgstruct-mode -1)
  8145. (mapc (lambda(v)
  8146. (set (make-local-variable (car v))
  8147. (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
  8148. org-fb-vars))
  8149. (orgstruct-mode 1)
  8150. (setq org-fb-vars nil)
  8151. (unless org-local-vars
  8152. (setq org-local-vars (org-get-local-variables)))
  8153. (let (var val)
  8154. (mapc
  8155. (lambda (x)
  8156. (when (string-match
  8157. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
  8158. (symbol-name (car x)))
  8159. (setq var (car x) val (nth 1 x))
  8160. (push (list var `(quote ,(eval var))) org-fb-vars)
  8161. (set (make-local-variable var)
  8162. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8163. org-local-vars)
  8164. (setq-local orgstruct-is-++ t))))
  8165. ;;;###autoload
  8166. (defun turn-on-orgstruct++ ()
  8167. "Unconditionally turn on `orgstruct++-mode'."
  8168. (orgstruct++-mode 1))
  8169. (defun orgstruct-error ()
  8170. "Error when there is no default binding for a structure key."
  8171. (interactive)
  8172. (funcall (if (fboundp 'user-error)
  8173. 'user-error
  8174. 'error)
  8175. "This key has no function outside structure elements"))
  8176. (defun orgstruct-setup ()
  8177. "Setup orgstruct keymap."
  8178. (dolist (cell '((org-demote . t)
  8179. (org-metaleft . t)
  8180. (org-metaright . t)
  8181. (org-promote . t)
  8182. (org-shiftmetaleft . t)
  8183. (org-shiftmetaright . t)
  8184. org-backward-element
  8185. org-backward-heading-same-level
  8186. org-ctrl-c-ret
  8187. org-ctrl-c-minus
  8188. org-ctrl-c-star
  8189. org-cycle
  8190. org-forward-heading-same-level
  8191. org-insert-heading
  8192. org-insert-heading-respect-content
  8193. org-kill-note-or-show-branches
  8194. org-mark-subtree
  8195. org-meta-return
  8196. org-metadown
  8197. org-metaup
  8198. org-narrow-to-subtree
  8199. org-promote-subtree
  8200. org-reveal
  8201. org-shiftdown
  8202. org-shiftleft
  8203. org-shiftmetadown
  8204. org-shiftmetaup
  8205. org-shiftright
  8206. org-shifttab
  8207. org-shifttab
  8208. org-shiftup
  8209. org-show-children
  8210. org-show-subtree
  8211. org-sort
  8212. org-up-element
  8213. outline-demote
  8214. outline-next-visible-heading
  8215. outline-previous-visible-heading
  8216. outline-promote
  8217. outline-up-heading))
  8218. (let ((f (or (car-safe cell) cell))
  8219. (disable-when-heading-prefix (cdr-safe cell)))
  8220. (when (fboundp f)
  8221. (let ((new-bindings))
  8222. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8223. (where-is-internal f outline-mode-map)))
  8224. (push binding new-bindings)
  8225. ;; TODO use local-function-key-map
  8226. (dolist (rep '(("<tab>" . "TAB")
  8227. ("<return>" . "RET")
  8228. ("<escape>" . "ESC")
  8229. ("<delete>" . "DEL")))
  8230. (setq binding (read-kbd-macro
  8231. (let ((case-fold-search))
  8232. (replace-regexp-in-string
  8233. (regexp-quote (cdr rep))
  8234. (car rep)
  8235. (key-description binding)))))
  8236. (pushnew binding new-bindings :test 'equal)))
  8237. (dolist (binding new-bindings)
  8238. (let ((key (lookup-key orgstruct-mode-map binding)))
  8239. (when (or (not key) (numberp key))
  8240. (ignore-errors
  8241. (org-defkey orgstruct-mode-map
  8242. binding
  8243. (orgstruct-make-binding
  8244. f binding disable-when-heading-prefix))))))))))
  8245. (run-hooks 'orgstruct-setup-hook))
  8246. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8247. "Create a function for binding in the structure minor mode.
  8248. FUN is the command to call inside a table. KEY is the key that
  8249. should be checked in for a command to execute outside of tables.
  8250. Non-nil `disable-when-heading-prefix' means to disable the command
  8251. if `orgstruct-heading-prefix-regexp' is not empty."
  8252. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8253. (let ((nname name)
  8254. (i 0))
  8255. (while (fboundp (intern nname))
  8256. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8257. (setq name (intern nname)))
  8258. (eval
  8259. (let ((bindings '((org-heading-regexp
  8260. (concat "^"
  8261. orgstruct-heading-prefix-regexp
  8262. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8263. (org-outline-regexp
  8264. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8265. (org-outline-regexp-bol
  8266. (concat "^" org-outline-regexp))
  8267. (outline-regexp org-outline-regexp)
  8268. (outline-heading-end-regexp "\n")
  8269. (outline-level 'org-outline-level)
  8270. (outline-heading-alist))))
  8271. `(defun ,name (arg)
  8272. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8273. "Outside of structure, run the binding of `"
  8274. (key-description key) "'."
  8275. (when disable-when-heading-prefix
  8276. (concat
  8277. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8278. "back to the default binding due to limitations of Org's implementation of\n"
  8279. "`" (symbol-name fun) "'.")))
  8280. (interactive "p")
  8281. (let* ((disable
  8282. ,(and disable-when-heading-prefix
  8283. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8284. (fallback
  8285. (or disable
  8286. (not
  8287. (let* ,bindings
  8288. (org-context-p 'headline 'item
  8289. ,(when (memq fun
  8290. '(org-insert-heading
  8291. org-insert-heading-respect-content
  8292. org-meta-return))
  8293. '(when orgstruct-is-++
  8294. 'item-body))))))))
  8295. (if fallback
  8296. (let* ((orgstruct-mode)
  8297. (binding
  8298. (let ((key ,key))
  8299. (catch 'exit
  8300. (dolist
  8301. (rep
  8302. '(nil
  8303. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8304. ("<\\([^>]*\\)return>" . "\\1RET")
  8305. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8306. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8307. nil)
  8308. (when rep
  8309. (setq key (read-kbd-macro
  8310. (let ((case-fold-search))
  8311. (replace-regexp-in-string
  8312. (car rep)
  8313. (cdr rep)
  8314. (key-description key))))))
  8315. (when (key-binding key)
  8316. (throw 'exit (key-binding key))))))))
  8317. (if (keymapp binding)
  8318. (org-set-transient-map binding)
  8319. (let ((func (or binding
  8320. (unless disable
  8321. 'orgstruct-error))))
  8322. (when func
  8323. (call-interactively func)))))
  8324. (org-run-like-in-org-mode
  8325. (lambda ()
  8326. (interactive)
  8327. (let* ,bindings
  8328. (call-interactively ',fun)))))))))
  8329. name))
  8330. (defun org-contextualize-keys (alist contexts)
  8331. "Return valid elements in ALIST depending on CONTEXTS.
  8332. `org-agenda-custom-commands' or `org-capture-templates' are the
  8333. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8334. or `org-capture-templates-contexts' are the associated contexts
  8335. definitions."
  8336. (let ((contexts
  8337. ;; normalize contexts
  8338. (mapcar
  8339. (lambda(c) (cond ((listp (cadr c))
  8340. (list (car c) (car c) (cadr c)))
  8341. ((string= "" (cadr c))
  8342. (list (car c) (car c) (caddr c)))
  8343. (t c)))
  8344. contexts))
  8345. (a alist) r s)
  8346. ;; loop over all commands or templates
  8347. (dolist (c a)
  8348. (let (vrules repl)
  8349. (cond
  8350. ((not (assoc (car c) contexts))
  8351. (push c r))
  8352. ((and (assoc (car c) contexts)
  8353. (setq vrules (org-contextualize-validate-key
  8354. (car c) contexts)))
  8355. (mapc (lambda (vr)
  8356. (unless (equal (car vr) (cadr vr))
  8357. (setq repl vr)))
  8358. vrules)
  8359. (if (not repl) (push c r)
  8360. (push (cadr repl) s)
  8361. (push
  8362. (cons (car c)
  8363. (cdr (or (assoc (cadr repl) alist)
  8364. (error "Undefined key `%s' as contextual replacement for `%s'"
  8365. (cadr repl) (car c)))))
  8366. r))))))
  8367. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8368. (delq
  8369. nil
  8370. (delete-dups
  8371. (mapcar (lambda (x)
  8372. (let ((tpl (car x)))
  8373. (unless (delq
  8374. nil
  8375. (mapcar (lambda (y)
  8376. (equal y tpl))
  8377. s))
  8378. x)))
  8379. (reverse r))))))
  8380. (defun org-contextualize-validate-key (key contexts)
  8381. "Check CONTEXTS for agenda or capture KEY."
  8382. (let (res)
  8383. (dolist (r contexts)
  8384. (dolist (rr (car (last r)))
  8385. (when
  8386. (and (equal key (car r))
  8387. (if (functionp rr) (funcall rr)
  8388. (or (and (eq (car rr) 'in-file)
  8389. (buffer-file-name)
  8390. (string-match (cdr rr) (buffer-file-name)))
  8391. (and (eq (car rr) 'in-mode)
  8392. (string-match (cdr rr) (symbol-name major-mode)))
  8393. (and (eq (car rr) 'in-buffer)
  8394. (string-match (cdr rr) (buffer-name)))
  8395. (when (and (eq (car rr) 'not-in-file)
  8396. (buffer-file-name))
  8397. (not (string-match (cdr rr) (buffer-file-name))))
  8398. (when (eq (car rr) 'not-in-mode)
  8399. (not (string-match (cdr rr) (symbol-name major-mode))))
  8400. (when (eq (car rr) 'not-in-buffer)
  8401. (not (string-match (cdr rr) (buffer-name)))))))
  8402. (push r res))))
  8403. (delete-dups (delq nil res))))
  8404. (defun org-context-p (&rest contexts)
  8405. "Check if local context is any of CONTEXTS.
  8406. Possible values in the list of contexts are `table', `headline', and `item'."
  8407. (let ((pos (point)))
  8408. (goto-char (point-at-bol))
  8409. (prog1 (or (and (memq 'table contexts)
  8410. (looking-at "[ \t]*|"))
  8411. (and (memq 'headline contexts)
  8412. (looking-at org-outline-regexp))
  8413. (and (memq 'item contexts)
  8414. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8415. (and (memq 'item-body contexts)
  8416. (org-in-item-p)))
  8417. (goto-char pos))))
  8418. (defconst org-unique-local-variables
  8419. '(org-element--cache
  8420. org-element--cache-objects
  8421. org-element--cache-sync-keys
  8422. org-element--cache-sync-requests
  8423. org-element--cache-sync-timer)
  8424. "List of local variables that cannot be transferred to another buffer.")
  8425. (defun org-get-local-variables ()
  8426. "Return a list of all local variables in an Org mode buffer."
  8427. (delq nil
  8428. (mapcar
  8429. (lambda (x)
  8430. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8431. (name (car binding)))
  8432. (and (not (get name 'org-state))
  8433. (not (memq name org-unique-local-variables))
  8434. (string-match-p
  8435. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8436. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8437. (symbol-name name))
  8438. binding)))
  8439. (with-temp-buffer
  8440. (org-mode)
  8441. (buffer-local-variables)))))
  8442. (defun org-clone-local-variables (from-buffer &optional regexp)
  8443. "Clone local variables from FROM-BUFFER.
  8444. Optional argument REGEXP selects variables to clone."
  8445. (dolist (pair (buffer-local-variables from-buffer))
  8446. (let ((name (car pair)))
  8447. (when (and (symbolp name)
  8448. (not (memq name org-unique-local-variables))
  8449. (or (null regexp) (string-match regexp (symbol-name name))))
  8450. (set (make-local-variable name) (cdr pair))))))
  8451. ;;;###autoload
  8452. (defun org-run-like-in-org-mode (cmd)
  8453. "Run a command, pretending that the current buffer is in Org-mode.
  8454. This will temporarily bind local variables that are typically bound in
  8455. Org-mode to the values they have in Org-mode, and then interactively
  8456. call CMD."
  8457. (org-load-modules-maybe)
  8458. (unless org-local-vars
  8459. (setq org-local-vars (org-get-local-variables)))
  8460. (let (binds)
  8461. (dolist (var org-local-vars)
  8462. (when (or (not (boundp (car var)))
  8463. (eq (symbol-value (car var))
  8464. (default-value (car var))))
  8465. (push (list (car var) `(quote ,(cadr var))) binds)))
  8466. (eval `(let ,binds
  8467. (call-interactively (quote ,cmd))))))
  8468. (defun org-get-category (&optional pos force-refresh)
  8469. "Get the category applying to position POS."
  8470. (save-match-data
  8471. (when force-refresh (org-refresh-category-properties))
  8472. (let ((pos (or pos (point))))
  8473. (or (get-text-property pos 'org-category)
  8474. (progn (org-refresh-category-properties)
  8475. (get-text-property pos 'org-category))))))
  8476. ;;; Refresh properties
  8477. (defun org-refresh-properties (dprop tprop)
  8478. "Refresh buffer text properties.
  8479. DPROP is the drawer property and TPROP is either the
  8480. corresponding text property to set, or an alist with each element
  8481. being a text property (as a symbol) and a function to apply to
  8482. the value of the drawer property."
  8483. (let ((case-fold-search t)
  8484. (inhibit-read-only t))
  8485. (org-with-silent-modifications
  8486. (save-excursion
  8487. (save-restriction
  8488. (widen)
  8489. (goto-char (point-min))
  8490. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8491. (org-refresh-property tprop (org-match-string-no-properties 1))))))))
  8492. (defun org-refresh-property (tprop p)
  8493. "Refresh the buffer text property TPROP from the drawer property P.
  8494. The refresh happens only for the current tree (not subtree)."
  8495. (unless (org-before-first-heading-p)
  8496. (save-excursion
  8497. (org-back-to-heading t)
  8498. (if (symbolp tprop)
  8499. ;; TPROP is a text property symbol
  8500. (put-text-property
  8501. (point) (or (outline-next-heading) (point-max)) tprop p)
  8502. ;; TPROP is an alist with (properties . function) elements
  8503. (dolist (al tprop)
  8504. (save-excursion
  8505. (put-text-property
  8506. (line-beginning-position) (or (outline-next-heading) (point-max))
  8507. (car al)
  8508. (funcall (cdr al) p))))))))
  8509. (defun org-refresh-category-properties ()
  8510. "Refresh category text properties in the buffer."
  8511. (let ((case-fold-search t)
  8512. (inhibit-read-only t)
  8513. (default-category
  8514. (cond ((null org-category)
  8515. (if buffer-file-name
  8516. (file-name-sans-extension
  8517. (file-name-nondirectory buffer-file-name))
  8518. "???"))
  8519. ((symbolp org-category) (symbol-name org-category))
  8520. (t org-category))))
  8521. (org-with-silent-modifications
  8522. (org-with-wide-buffer
  8523. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8524. ;; This is the default category for the buffer. If none is
  8525. ;; found, fall-back to `org-category' or buffer file name.
  8526. (put-text-property
  8527. (point-min) (point-max)
  8528. 'org-category
  8529. (catch 'buffer-category
  8530. (goto-char (point-max))
  8531. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8532. (let ((element (org-element-at-point)))
  8533. (when (eq (org-element-type element) 'keyword)
  8534. (throw 'buffer-category
  8535. (org-element-property :value element)))))
  8536. default-category))
  8537. ;; Set sub-tree specific categories.
  8538. (goto-char (point-min))
  8539. (let ((regexp (org-re-property "CATEGORY")))
  8540. (while (re-search-forward regexp nil t)
  8541. (let ((value (org-match-string-no-properties 3)))
  8542. (when (org-at-property-p)
  8543. (put-text-property
  8544. (save-excursion (org-back-to-heading t) (point))
  8545. (save-excursion (org-end-of-subtree t t) (point))
  8546. 'org-category
  8547. value)))))))))
  8548. (defun org-refresh-stats-properties ()
  8549. "Refresh stats text properties in the buffer."
  8550. (let (stats)
  8551. (org-with-silent-modifications
  8552. (save-excursion
  8553. (save-restriction
  8554. (widen)
  8555. (goto-char (point-min))
  8556. (while (re-search-forward
  8557. (concat org-outline-regexp-bol ".*"
  8558. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8559. nil t)
  8560. (setq stats (cond ((equal (match-string 3) "0") 0)
  8561. ((match-string 2)
  8562. (/ (* (string-to-number (match-string 2)) 100)
  8563. (string-to-number (match-string 3))))
  8564. (t (string-to-number (match-string 1)))))
  8565. (org-back-to-heading t)
  8566. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8567. 'org-stats stats)))))))
  8568. (defun org-refresh-effort-properties ()
  8569. "Refresh effort properties"
  8570. (org-refresh-properties
  8571. org-effort-property
  8572. '((effort . identity)
  8573. (effort-minutes . org-duration-string-to-minutes))))
  8574. ;;;; Link Stuff
  8575. ;;; Link abbreviations
  8576. (defun org-link-expand-abbrev (link)
  8577. "Apply replacements as defined in `org-link-abbrev-alist'."
  8578. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8579. (let* ((key (match-string 1 link))
  8580. (as (or (assoc key org-link-abbrev-alist-local)
  8581. (assoc key org-link-abbrev-alist)))
  8582. (tag (and (match-end 2) (match-string 3 link)))
  8583. rpl)
  8584. (if (not as)
  8585. link
  8586. (setq rpl (cdr as))
  8587. (cond
  8588. ((symbolp rpl) (funcall rpl tag))
  8589. ((string-match "%(\\([^)]+\\))" rpl)
  8590. (replace-match
  8591. (save-match-data
  8592. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8593. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8594. ((string-match "%h" rpl)
  8595. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8596. (t (concat rpl tag)))))
  8597. link))
  8598. ;;; Storing and inserting links
  8599. (defvar org-insert-link-history nil
  8600. "Minibuffer history for links inserted with `org-insert-link'.")
  8601. (defvar org-stored-links nil
  8602. "Contains the links stored with `org-store-link'.")
  8603. (defvar org-store-link-plist nil
  8604. "Plist with info about the most recently link created with `org-store-link'.")
  8605. (defvar org-link-protocols nil
  8606. "Link protocols added to Org-mode using `org-add-link-type'.")
  8607. (defvar org-store-link-functions nil
  8608. "List of functions that are called to create and store a link.
  8609. Each function will be called in turn until one returns a non-nil
  8610. value. Each function should check if it is responsible for creating
  8611. this link (for example by looking at the major mode).
  8612. If not, it must exit and return nil.
  8613. If yes, it should return a non-nil value after a calling
  8614. `org-store-link-props' with a list of properties and values.
  8615. Special properties are:
  8616. :type The link prefix, like \"http\". This must be given.
  8617. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8618. This is obligatory as well.
  8619. :description Optional default description for the second pair
  8620. of brackets in an Org-mode link. The user can still change
  8621. this when inserting this link into an Org-mode buffer.
  8622. In addition to these, any additional properties can be specified
  8623. and then used in capture templates.")
  8624. (defun org-add-link-type (type &optional follow export)
  8625. "Add TYPE to the list of `org-link-types'.
  8626. Re-compute all regular expressions depending on `org-link-types'
  8627. FOLLOW and EXPORT are two functions.
  8628. FOLLOW should take the link path as the single argument and do whatever
  8629. is necessary to follow the link, for example find a file or display
  8630. a mail message.
  8631. EXPORT should format the link path for export to one of the export formats.
  8632. It should be a function accepting three arguments:
  8633. path the path of the link, the text after the prefix (like \"http:\")
  8634. desc the description of the link, if any
  8635. format the export format, a symbol like `html' or `latex' or `ascii'.
  8636. The function may use the FORMAT information to return different values
  8637. depending on the format. The return value will be put literally into
  8638. the exported file. If the return value is nil, this means Org should
  8639. do what it normally does with links which do not have EXPORT defined.
  8640. Org mode has a built-in default for exporting links. If you are happy with
  8641. this default, there is no need to define an export function for the link
  8642. type. For a simple example of an export function, see `org-bbdb.el'."
  8643. (add-to-list 'org-link-types type t)
  8644. (org-make-link-regexps)
  8645. (org-element-update-syntax)
  8646. (if (assoc type org-link-protocols)
  8647. (setcdr (assoc type org-link-protocols) (list follow export))
  8648. (push (list type follow export) org-link-protocols)))
  8649. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8650. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8651. ;;;###autoload
  8652. (defun org-store-link (arg)
  8653. "\\<org-mode-map>Store an org-link to the current location.
  8654. This link is added to `org-stored-links' and can later be inserted
  8655. into an Org buffer with \\[org-insert-link].
  8656. For some link types, a prefix ARG is interpreted.
  8657. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8658. For file links, ARG negates `org-context-in-file-links'.
  8659. A double prefix ARG force skipping storing functions that are not
  8660. part of Org's core.
  8661. A triple prefix ARG force storing a link for each line in the
  8662. active region."
  8663. (interactive "P")
  8664. (org-load-modules-maybe)
  8665. (if (and (equal arg '(64)) (org-region-active-p))
  8666. (save-excursion
  8667. (let ((end (region-end)))
  8668. (goto-char (region-beginning))
  8669. (set-mark (point))
  8670. (while (< (point-at-eol) end)
  8671. (move-end-of-line 1) (activate-mark)
  8672. (let (current-prefix-arg)
  8673. (call-interactively 'org-store-link))
  8674. (move-beginning-of-line 2)
  8675. (set-mark (point)))))
  8676. (org-with-limited-levels
  8677. (setq org-store-link-plist nil)
  8678. (let (link cpltxt desc description search
  8679. txt custom-id agenda-link sfuns sfunsn)
  8680. (cond
  8681. ;; Store a link using an external link type
  8682. ((and (not (equal arg '(16)))
  8683. (setq sfuns
  8684. (delq
  8685. nil (mapcar (lambda (f)
  8686. (let (fs) (if (funcall f) (push f fs))))
  8687. org-store-link-functions))
  8688. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8689. (or (and (cdr sfuns)
  8690. (funcall (intern
  8691. (completing-read
  8692. "Which function for creating the link? "
  8693. sfunsn nil t (car sfunsn)))))
  8694. (funcall (caar sfuns)))
  8695. (setq link (plist-get org-store-link-plist :link)
  8696. desc (or (plist-get org-store-link-plist
  8697. :description)
  8698. link))))
  8699. ;; Store a link from a source code buffer.
  8700. ((org-src-edit-buffer-p)
  8701. (cond
  8702. ((save-excursion
  8703. (beginning-of-line)
  8704. (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
  8705. "[ \t]*$")))
  8706. (setq link (format "(%s)" (org-match-string-no-properties 1))))
  8707. ((org-called-interactively-p 'any)
  8708. (let (label)
  8709. (while (or (not label)
  8710. (org-with-wide-buffer
  8711. (goto-char (point-min))
  8712. (re-search-forward
  8713. (regexp-quote (format org-coderef-label-format label))
  8714. nil t)))
  8715. (when label (message "Label exists already") (sit-for 2))
  8716. (setq label (read-string "Code line label: " label)))
  8717. (end-of-line)
  8718. (setq link (format org-coderef-label-format label))
  8719. (let ((gc (- 79 (length link))))
  8720. (if (< (current-column) gc) (org-move-to-column gc t)
  8721. (insert " ")))
  8722. (insert link)
  8723. (setq link (concat "(" label ")") desc nil)))
  8724. (t (setq link nil))))
  8725. ;; We are in the agenda, link to referenced location
  8726. ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8727. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8728. (get-text-property (point) 'org-marker))))
  8729. (when m
  8730. (org-with-point-at m
  8731. (setq agenda-link
  8732. (if (org-called-interactively-p 'any)
  8733. (call-interactively 'org-store-link)
  8734. (org-store-link nil)))))))
  8735. ((eq major-mode 'calendar-mode)
  8736. (let ((cd (calendar-cursor-to-date)))
  8737. (setq link
  8738. (format-time-string
  8739. (car org-time-stamp-formats)
  8740. (apply 'encode-time
  8741. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8742. nil nil nil))))
  8743. (org-store-link-props :type "calendar" :date cd)))
  8744. ((eq major-mode 'help-mode)
  8745. (setq link (concat "help:" (save-excursion
  8746. (goto-char (point-min))
  8747. (looking-at "^[^ ]+")
  8748. (match-string 0))))
  8749. (org-store-link-props :type "help"))
  8750. ((eq major-mode 'w3-mode)
  8751. (setq cpltxt (if (and (buffer-name)
  8752. (not (string-match "Untitled" (buffer-name))))
  8753. (buffer-name)
  8754. (url-view-url t))
  8755. link (url-view-url t))
  8756. (org-store-link-props :type "w3" :url (url-view-url t)))
  8757. ((eq major-mode 'image-mode)
  8758. (setq cpltxt (concat "file:"
  8759. (abbreviate-file-name buffer-file-name))
  8760. link cpltxt)
  8761. (org-store-link-props :type "image" :file buffer-file-name))
  8762. ;; In dired, store a link to the file of the current line
  8763. ((derived-mode-p 'dired-mode)
  8764. (let ((file (dired-get-filename nil t)))
  8765. (setq file (if file
  8766. (abbreviate-file-name
  8767. (expand-file-name (dired-get-filename nil t)))
  8768. ;; otherwise, no file so use current directory.
  8769. default-directory))
  8770. (setq cpltxt (concat "file:" file)
  8771. link cpltxt)))
  8772. ((setq search (run-hook-with-args-until-success
  8773. 'org-create-file-search-functions))
  8774. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8775. "::" search))
  8776. (setq cpltxt (or description link)))
  8777. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8778. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8779. (cond
  8780. ;; Store a link using the target at point
  8781. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8782. (setq cpltxt
  8783. (concat "file:"
  8784. (abbreviate-file-name
  8785. (buffer-file-name (buffer-base-buffer)))
  8786. "::" (match-string 1))
  8787. link cpltxt))
  8788. ((and (featurep 'org-id)
  8789. (or (eq org-id-link-to-org-use-id t)
  8790. (and (org-called-interactively-p 'any)
  8791. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8792. (and (eq org-id-link-to-org-use-id
  8793. 'create-if-interactive-and-no-custom-id)
  8794. (not custom-id))))
  8795. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8796. ;; Store a link using the ID at point
  8797. (setq link (condition-case nil
  8798. (prog1 (org-id-store-link)
  8799. (setq desc (or (plist-get org-store-link-plist
  8800. :description)
  8801. "")))
  8802. (error
  8803. ;; Probably before first headline, link only to file
  8804. (concat "file:"
  8805. (abbreviate-file-name
  8806. (buffer-file-name (buffer-base-buffer))))))))
  8807. (t
  8808. ;; Just link to current headline
  8809. (setq cpltxt (concat "file:"
  8810. (abbreviate-file-name
  8811. (buffer-file-name (buffer-base-buffer)))))
  8812. ;; Add a context search string
  8813. (when (org-xor org-context-in-file-links arg)
  8814. (let* ((ee (org-element-at-point))
  8815. (et (org-element-type ee))
  8816. (ev (plist-get (cadr ee) :value))
  8817. (ek (plist-get (cadr ee) :key))
  8818. (eok (and (stringp ek) (string-match "name" ek))))
  8819. (setq txt (cond
  8820. ((org-at-heading-p) nil)
  8821. ((and (eq et 'keyword) eok) ev)
  8822. ((org-region-active-p)
  8823. (buffer-substring (region-beginning) (region-end)))))
  8824. (when (or (null txt) (string-match "\\S-" txt))
  8825. (setq cpltxt
  8826. (concat cpltxt "::"
  8827. (condition-case nil
  8828. (org-make-org-heading-search-string txt)
  8829. (error "")))
  8830. desc (or (and (eq et 'keyword) eok ev)
  8831. (nth 4 (ignore-errors (org-heading-components)))
  8832. "NONE")))))
  8833. (when (string-match "::\\'" cpltxt)
  8834. (setq cpltxt (substring cpltxt 0 -2)))
  8835. (setq link cpltxt))))
  8836. ((buffer-file-name (buffer-base-buffer))
  8837. ;; Just link to this file here.
  8838. (setq cpltxt (concat "file:"
  8839. (abbreviate-file-name
  8840. (buffer-file-name (buffer-base-buffer)))))
  8841. ;; Add a context string.
  8842. (when (org-xor org-context-in-file-links arg)
  8843. (setq txt (if (org-region-active-p)
  8844. (buffer-substring (region-beginning) (region-end))
  8845. (buffer-substring (point-at-bol) (point-at-eol))))
  8846. ;; Only use search option if there is some text.
  8847. (when (string-match "\\S-" txt)
  8848. (setq cpltxt
  8849. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8850. desc "NONE")))
  8851. (setq link cpltxt))
  8852. ((org-called-interactively-p 'interactive)
  8853. (user-error "No method for storing a link from this buffer"))
  8854. (t (setq link nil)))
  8855. ;; We're done setting link and desc, clean up
  8856. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8857. (setq link (or link cpltxt)
  8858. desc (or desc cpltxt))
  8859. (cond ((equal desc "NONE") (setq desc nil))
  8860. ((and desc (string-match org-bracket-link-analytic-regexp desc))
  8861. (let ((d0 (match-string 3 desc))
  8862. (p0 (match-string 5 desc)))
  8863. (setq desc
  8864. (replace-regexp-in-string
  8865. org-bracket-link-regexp
  8866. (concat (or p0 d0)
  8867. (if (equal (length (match-string 0 desc))
  8868. (length desc)) "*" "")) desc)))))
  8869. ;; Return the link
  8870. (if (not (and (or (org-called-interactively-p 'any)
  8871. executing-kbd-macro)
  8872. link))
  8873. (or agenda-link (and link (org-make-link-string link desc)))
  8874. (push (list link desc) org-stored-links)
  8875. (message "Stored: %s" (or desc link))
  8876. (when custom-id
  8877. (setq link (concat "file:" (abbreviate-file-name
  8878. (buffer-file-name)) "::#" custom-id))
  8879. (push (list link desc) org-stored-links))
  8880. (car org-stored-links))))))
  8881. (defun org-store-link-props (&rest plist)
  8882. "Store link properties, extract names, addresses and dates."
  8883. (let ((x (plist-get plist :from)))
  8884. (when x
  8885. (let ((adr (mail-extract-address-components x)))
  8886. (setq plist (plist-put plist :fromname (car adr)))
  8887. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8888. (let ((x (plist-get plist :to)))
  8889. (when x
  8890. (let ((adr (mail-extract-address-components x)))
  8891. (setq plist (plist-put plist :toname (car adr)))
  8892. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8893. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8894. (when x
  8895. (setq plist (plist-put plist :date-timestamp
  8896. (format-time-string
  8897. (org-time-stamp-format t) x)))
  8898. (setq plist (plist-put plist :date-timestamp-inactive
  8899. (format-time-string
  8900. (org-time-stamp-format t t) x)))))
  8901. (let ((from (plist-get plist :from))
  8902. (to (plist-get plist :to)))
  8903. (when (and from to org-from-is-user-regexp)
  8904. (setq plist
  8905. (plist-put plist :fromto
  8906. (if (string-match org-from-is-user-regexp from)
  8907. (concat "to %t")
  8908. (concat "from %f"))))))
  8909. (setq org-store-link-plist plist))
  8910. (defun org-add-link-props (&rest plist)
  8911. "Add these properties to the link property list."
  8912. (let (key value)
  8913. (while plist
  8914. (setq key (pop plist) value (pop plist))
  8915. (setq org-store-link-plist
  8916. (plist-put org-store-link-plist key value)))))
  8917. (defun org-email-link-description (&optional fmt)
  8918. "Return the description part of an email link.
  8919. This takes information from `org-store-link-plist' and formats it
  8920. according to FMT (default from `org-email-link-description-format')."
  8921. (setq fmt (or fmt org-email-link-description-format))
  8922. (let* ((p org-store-link-plist)
  8923. (to (plist-get p :toaddress))
  8924. (from (plist-get p :fromaddress))
  8925. (table
  8926. (list
  8927. (cons "%c" (plist-get p :fromto))
  8928. (cons "%F" (plist-get p :from))
  8929. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8930. (cons "%T" (plist-get p :to))
  8931. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8932. (cons "%s" (plist-get p :subject))
  8933. (cons "%d" (plist-get p :date))
  8934. (cons "%m" (plist-get p :message-id)))))
  8935. (when (string-match "%c" fmt)
  8936. ;; Check if the user wrote this message
  8937. (if (and org-from-is-user-regexp from to
  8938. (save-match-data (string-match org-from-is-user-regexp from)))
  8939. (setq fmt (replace-match "to %t" t t fmt))
  8940. (setq fmt (replace-match "from %f" t t fmt))))
  8941. (org-replace-escapes fmt table)))
  8942. (defun org-make-org-heading-search-string (&optional string)
  8943. "Make search string for the current headline or STRING."
  8944. (let ((s (or string
  8945. (and (derived-mode-p 'org-mode)
  8946. (save-excursion
  8947. (org-back-to-heading t)
  8948. (org-element-property :raw-value (org-element-at-point))))))
  8949. (lines org-context-in-file-links))
  8950. (or string (setq s (concat "*" s))) ; Add * for headlines
  8951. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8952. (when (and string (integerp lines) (> lines 0))
  8953. (let ((slines (org-split-string s "\n")))
  8954. (when (< lines (length slines))
  8955. (setq s (mapconcat
  8956. 'identity
  8957. (reverse (nthcdr (- (length slines) lines)
  8958. (reverse slines))) "\n")))))
  8959. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  8960. (defun org-make-link-string (link &optional description)
  8961. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8962. (unless (org-string-nw-p link) (error "Empty link"))
  8963. (let ((uri (cond ((string-match org-link-types-re link)
  8964. (concat (match-string 1 link)
  8965. (org-link-escape (substring link (match-end 1)))))
  8966. ;; For readability, url-encode internal links only
  8967. ;; when absolutely needed (i.e, when they contain
  8968. ;; square brackets). File links however, are
  8969. ;; encoded since, e.g., spaces are significant.
  8970. ((or (file-name-absolute-p link)
  8971. (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
  8972. (org-link-escape link))
  8973. (t link)))
  8974. (description
  8975. (and (org-string-nw-p description)
  8976. ;; Remove brackets from description, as they are fatal.
  8977. (replace-regexp-in-string
  8978. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8979. (org-trim description)))))
  8980. (format "[[%s]%s]"
  8981. uri
  8982. (if description (format "[%s]" description) ""))))
  8983. (defconst org-link-escape-chars
  8984. ;;%20 %5B %5D %25
  8985. '(?\s ?\[ ?\] ?%)
  8986. "List of characters that should be escaped in a link when stored to Org.
  8987. This is the list that is used for internal purposes.")
  8988. (defconst org-link-escape-chars-browser
  8989. ;;%20 %22
  8990. '(?\s ?\")
  8991. "List of characters to be escaped before handing over to the browser.
  8992. If you consider using this constant then you probably want to use
  8993. the function `org-link-escape-browser' instead. See there why
  8994. this constant is a candidate to be removed once Org drops support
  8995. for Emacs 24.1 and 24.2.")
  8996. (defun org-link-escape (text &optional table merge)
  8997. "Return percent escaped representation of TEXT.
  8998. TEXT is a string with the text to escape.
  8999. Optional argument TABLE is a list with characters that should be
  9000. escaped. When nil, `org-link-escape-chars' is used.
  9001. If optional argument MERGE is set, merge TABLE into
  9002. `org-link-escape-chars'."
  9003. (let ((characters-to-encode
  9004. (cond ((null table) org-link-escape-chars)
  9005. (merge (append org-link-escape-chars table))
  9006. (t table))))
  9007. (mapconcat
  9008. (lambda (c)
  9009. (if (or (memq c characters-to-encode)
  9010. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9011. (mapconcat (lambda (e) (format "%%%.2X" e))
  9012. (or (encode-coding-char c 'utf-8)
  9013. (error "Unable to percent escape character: %c" c))
  9014. "")
  9015. (char-to-string c)))
  9016. text "")))
  9017. (defun org-link-escape-browser (text)
  9018. "Escape some characters before handing over to the browser.
  9019. This function is a candidate to be removed together with the
  9020. constant `org-link-escape-chars-browser' once Org drops support
  9021. for Emacs 24.1 and 24.2. All calls to this function will have to
  9022. be replaced with `url-encode-url' which is available since Emacs
  9023. 24.3.1."
  9024. ;; Example with the Org link
  9025. ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
  9026. ;; to open the browser with +subject:"Release 8.2" filled into the
  9027. ;; query field: In this case the variable TEXT contains the
  9028. ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
  9029. ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
  9030. ;; `org-link-escape' with `org-link-escape-chars-browser' converts
  9031. ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
  9032. (if (fboundp 'url-encode-url)
  9033. (url-encode-url text)
  9034. (if (org-string-match-p
  9035. (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
  9036. text)
  9037. (org-link-escape text org-link-escape-chars-browser)
  9038. text)))
  9039. (defun org-link-unescape (str)
  9040. "Unhex hexified Unicode parts in string STR.
  9041. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9042. reciprocal of `org-link-escape', which see."
  9043. (if (org-string-nw-p str)
  9044. (replace-regexp-in-string
  9045. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9046. str))
  9047. (defun org-link-unescape-compound (hex)
  9048. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9049. Note: this function also decodes single byte encodings like
  9050. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9051. (save-match-data
  9052. (let* ((bytes (cdr (split-string hex "%")))
  9053. (ret "")
  9054. (eat 0)
  9055. (sum 0))
  9056. (while bytes
  9057. (let* ((val (string-to-number (pop bytes) 16))
  9058. (shift-xor
  9059. (if (= 0 eat)
  9060. (cond
  9061. ((>= val 252) (cons 6 252))
  9062. ((>= val 248) (cons 5 248))
  9063. ((>= val 240) (cons 4 240))
  9064. ((>= val 224) (cons 3 224))
  9065. ((>= val 192) (cons 2 192))
  9066. (t (cons 0 0)))
  9067. (cons 6 128))))
  9068. (when (>= val 192) (setq eat (car shift-xor)))
  9069. (setq val (logxor val (cdr shift-xor)))
  9070. (setq sum (+ (lsh sum (car shift-xor)) val))
  9071. (when (> eat 0) (setq eat (- eat 1)))
  9072. (cond
  9073. ((= 0 eat) ;multi byte
  9074. (setq ret (concat ret (org-char-to-string sum)))
  9075. (setq sum 0))
  9076. ((not bytes) ; single byte(s)
  9077. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9078. ret)))
  9079. (defun org-link-unescape-single-byte-sequence (hex)
  9080. "Unhexify hex-encoded single byte character sequences."
  9081. (mapconcat (lambda (byte)
  9082. (char-to-string (string-to-number byte 16)))
  9083. (cdr (split-string hex "%")) ""))
  9084. (defun org-xor (a b)
  9085. "Exclusive or."
  9086. (if a (not b) b))
  9087. (defun org-fixup-message-id-for-http (s)
  9088. "Replace special characters in a message id, so it can be used in an http query."
  9089. (when (string-match "%" s)
  9090. (setq s (mapconcat (lambda (c)
  9091. (if (eq c ?%)
  9092. "%25"
  9093. (char-to-string c)))
  9094. s "")))
  9095. (while (string-match "<" s)
  9096. (setq s (replace-match "%3C" t t s)))
  9097. (while (string-match ">" s)
  9098. (setq s (replace-match "%3E" t t s)))
  9099. (while (string-match "@" s)
  9100. (setq s (replace-match "%40" t t s)))
  9101. s)
  9102. (defun org-link-prettify (link)
  9103. "Return a human-readable representation of LINK.
  9104. The car of LINK must be a raw link.
  9105. The cdr of LINK must be either a link description or nil."
  9106. (let ((desc (or (cadr link) "<no description>")))
  9107. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9108. "<" (car link) ">")))
  9109. ;;;###autoload
  9110. (defun org-insert-link-global ()
  9111. "Insert a link like Org-mode does.
  9112. This command can be called in any mode to insert a link in Org-mode syntax."
  9113. (interactive)
  9114. (org-load-modules-maybe)
  9115. (org-run-like-in-org-mode 'org-insert-link))
  9116. (defun org-insert-all-links (arg &optional pre post)
  9117. "Insert all links in `org-stored-links'.
  9118. When a universal prefix, do not delete the links from `org-stored-links'.
  9119. When `ARG' is a number, insert the last N link(s).
  9120. `PRE' and `POST' are optional arguments to define a string to
  9121. prepend or to append."
  9122. (interactive "P")
  9123. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9124. (links (copy-seq org-stored-links))
  9125. (pr (or pre "- "))
  9126. (po (or post "\n"))
  9127. (cnt 1) l)
  9128. (if (null org-stored-links)
  9129. (message "No link to insert")
  9130. (while (and (or (listp arg) (>= arg cnt))
  9131. (setq l (if (listp arg)
  9132. (pop links)
  9133. (pop org-stored-links))))
  9134. (setq cnt (1+ cnt))
  9135. (insert pr)
  9136. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9137. (insert po)))))
  9138. (defun org-insert-last-stored-link (arg)
  9139. "Insert the last link stored in `org-stored-links'."
  9140. (interactive "p")
  9141. (org-insert-all-links arg "" "\n"))
  9142. (defun org-link-fontify-links-to-this-file ()
  9143. "Fontify links to the current file in `org-stored-links'."
  9144. (let ((f (buffer-file-name)) a b)
  9145. (setq a (mapcar (lambda(l)
  9146. (let ((ll (car l)))
  9147. (when (and (string-match "^file:\\(.+\\)::" ll)
  9148. (equal f (expand-file-name (match-string 1 ll))))
  9149. ll)))
  9150. org-stored-links))
  9151. (when (featurep 'org-id)
  9152. (setq b (mapcar (lambda(l)
  9153. (let ((ll (car l)))
  9154. (when (and (string-match "^id:\\(.+\\)$" ll)
  9155. (equal f (expand-file-name
  9156. (or (org-id-find-id-file
  9157. (match-string 1 ll)) ""))))
  9158. ll)))
  9159. org-stored-links)))
  9160. (mapcar (lambda(l)
  9161. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9162. (delq nil (append a b)))))
  9163. (defvar org--links-history nil)
  9164. (defun org-insert-link (&optional complete-file link-location default-description)
  9165. "Insert a link. At the prompt, enter the link.
  9166. Completion can be used to insert any of the link protocol prefixes like
  9167. http or ftp in use.
  9168. The history can be used to select a link previously stored with
  9169. `org-store-link'. When the empty string is entered (i.e. if you just
  9170. press RET at the prompt), the link defaults to the most recently
  9171. stored link. As SPC triggers completion in the minibuffer, you need to
  9172. use M-SPC or C-q SPC to force the insertion of a space character.
  9173. You will also be prompted for a description, and if one is given, it will
  9174. be displayed in the buffer instead of the link.
  9175. If there is already a link at point, this command will allow you to edit link
  9176. and description parts.
  9177. With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
  9178. be selected using completion. The path to the file will be relative to the
  9179. current directory if the file is in the current directory or a subdirectory.
  9180. Otherwise, the link will be the absolute path as completed in the minibuffer
  9181. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9182. option `org-link-file-path-type'.
  9183. With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
  9184. the current directory or below.
  9185. With three \\[universal-argument] prefixes, negate the meaning of
  9186. `org-keep-stored-link-after-insertion'.
  9187. If `org-make-link-description-function' is non-nil, this function will be
  9188. called with the link target, and the result will be the default
  9189. link description.
  9190. If the LINK-LOCATION parameter is non-nil, this value will be
  9191. used as the link location instead of reading one interactively.
  9192. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9193. be used as the default description."
  9194. (interactive "P")
  9195. (let* ((wcf (current-window-configuration))
  9196. (origbuf (current-buffer))
  9197. (region (when (org-region-active-p)
  9198. (buffer-substring (region-beginning) (region-end))))
  9199. (remove (and region (list (region-beginning) (region-end))))
  9200. (desc region)
  9201. (link link-location)
  9202. (abbrevs org-link-abbrev-alist-local)
  9203. entry all-prefixes auto-desc)
  9204. (cond
  9205. (link-location) ; specified by arg, just use it.
  9206. ((org-in-regexp org-bracket-link-regexp 1)
  9207. ;; We do have a link at point, and we are going to edit it.
  9208. (setq remove (list (match-beginning 0) (match-end 0)))
  9209. (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
  9210. (setq link (read-string "Link: "
  9211. (org-link-unescape
  9212. (org-match-string-no-properties 1)))))
  9213. ((or (org-in-regexp org-angle-link-re)
  9214. (org-in-regexp org-plain-link-re))
  9215. ;; Convert to bracket link
  9216. (setq remove (list (match-beginning 0) (match-end 0))
  9217. link (read-string "Link: "
  9218. (org-remove-angle-brackets (match-string 0)))))
  9219. ((member complete-file '((4) (16)))
  9220. ;; Completing read for file names.
  9221. (setq link (org-file-complete-link complete-file)))
  9222. (t
  9223. ;; Read link, with completion for stored links.
  9224. (org-link-fontify-links-to-this-file)
  9225. (org-switch-to-buffer-other-window "*Org Links*")
  9226. (with-current-buffer "*Org Links*"
  9227. (erase-buffer)
  9228. (insert "Insert a link.
  9229. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9230. (when org-stored-links
  9231. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9232. (insert (mapconcat 'org-link-prettify
  9233. (reverse org-stored-links) "\n")))
  9234. (goto-char (point-min)))
  9235. (let ((cw (selected-window)))
  9236. (select-window (get-buffer-window "*Org Links*" 'visible))
  9237. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9238. (unless (pos-visible-in-window-p (point-max))
  9239. (org-fit-window-to-buffer))
  9240. (and (window-live-p cw) (select-window cw)))
  9241. (setq all-prefixes (append (mapcar 'car abbrevs)
  9242. (mapcar 'car org-link-abbrev-alist)
  9243. org-link-types))
  9244. (unwind-protect
  9245. ;; Fake a link history, containing the stored links.
  9246. (let ((org--links-history
  9247. (append (mapcar #'car org-stored-links)
  9248. org-insert-link-history)))
  9249. (setq link
  9250. (org-completing-read
  9251. "Link: "
  9252. (append
  9253. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9254. (mapcar #'car org-stored-links))
  9255. nil nil nil
  9256. 'org--links-history
  9257. (caar org-stored-links)))
  9258. (unless (org-string-nw-p link) (user-error "No link selected"))
  9259. (dolist (l org-stored-links)
  9260. (when (equal link (cadr l))
  9261. (setq link (car l))
  9262. (setq auto-desc t)))
  9263. (when (or (member link all-prefixes)
  9264. (and (equal ":" (substring link -1))
  9265. (member (substring link 0 -1) all-prefixes)
  9266. (setq link (substring link 0 -1))))
  9267. (setq link (with-current-buffer origbuf
  9268. (org-link-try-special-completion link)))))
  9269. (set-window-configuration wcf)
  9270. (kill-buffer "*Org Links*"))
  9271. (setq entry (assoc link org-stored-links))
  9272. (or entry (push link org-insert-link-history))
  9273. (setq desc (or desc (nth 1 entry)))))
  9274. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9275. (not org-keep-stored-link-after-insertion))
  9276. (setq org-stored-links (delq (assoc link org-stored-links)
  9277. org-stored-links)))
  9278. (when (and (string-match org-plain-link-re link)
  9279. (not (string-match org-ts-regexp link)))
  9280. ;; URL-like link, normalize the use of angular brackets.
  9281. (setq link (org-remove-angle-brackets link)))
  9282. ;; Check if we are linking to the current file with a search
  9283. ;; option If yes, simplify the link by using only the search
  9284. ;; option.
  9285. (when (and buffer-file-name
  9286. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9287. (let* ((path (match-string 1 link))
  9288. (case-fold-search nil)
  9289. (search (match-string 2 link)))
  9290. (save-match-data
  9291. (when (equal (file-truename buffer-file-name) (file-truename path))
  9292. ;; We are linking to this same file, with a search option
  9293. (setq link search)))))
  9294. ;; Check if we can/should use a relative path. If yes, simplify the link
  9295. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9296. (let* ((type (match-string 1 link))
  9297. (path (match-string 2 link))
  9298. (origpath path)
  9299. (case-fold-search nil))
  9300. (cond
  9301. ((or (eq org-link-file-path-type 'absolute)
  9302. (equal complete-file '(16)))
  9303. (setq path (abbreviate-file-name (expand-file-name path))))
  9304. ((eq org-link-file-path-type 'noabbrev)
  9305. (setq path (expand-file-name path)))
  9306. ((eq org-link-file-path-type 'relative)
  9307. (setq path (file-relative-name path)))
  9308. (t
  9309. (save-match-data
  9310. (if (string-match (concat "^" (regexp-quote
  9311. (expand-file-name
  9312. (file-name-as-directory
  9313. default-directory))))
  9314. (expand-file-name path))
  9315. ;; We are linking a file with relative path name.
  9316. (setq path (substring (expand-file-name path)
  9317. (match-end 0)))
  9318. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9319. (setq link (concat type path))
  9320. (when (equal desc origpath)
  9321. (setq desc path))))
  9322. (if org-make-link-description-function
  9323. (setq desc
  9324. (or (condition-case nil
  9325. (funcall org-make-link-description-function link desc)
  9326. (error (progn (message "Can't get link description from `%s'"
  9327. (symbol-name org-make-link-description-function))
  9328. (sit-for 2) nil)))
  9329. (read-string "Description: " default-description)))
  9330. (if default-description (setq desc default-description)
  9331. (setq desc (or (and auto-desc desc)
  9332. (read-string "Description: " desc)))))
  9333. (unless (string-match "\\S-" desc) (setq desc nil))
  9334. (when remove (apply 'delete-region remove))
  9335. (insert (org-make-link-string link desc))
  9336. ;; Redisplay so as the new link has proper invisible characters.
  9337. (sit-for 0)))
  9338. (defun org-link-try-special-completion (type)
  9339. "If there is completion support for link type TYPE, offer it."
  9340. (let ((fun (intern (concat "org-" type "-complete-link"))))
  9341. (if (functionp fun)
  9342. (funcall fun)
  9343. (read-string "Link (no completion support): " (concat type ":")))))
  9344. (defun org-file-complete-link (&optional arg)
  9345. "Create a file link using completion."
  9346. (let ((file (org-iread-file-name "File: "))
  9347. (pwd (file-name-as-directory (expand-file-name ".")))
  9348. (pwd1 (file-name-as-directory (abbreviate-file-name
  9349. (expand-file-name ".")))))
  9350. (cond ((equal arg '(16))
  9351. (concat "file:"
  9352. (abbreviate-file-name (expand-file-name file))))
  9353. ((string-match
  9354. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9355. (concat "file:" (match-string 1 file)))
  9356. ((string-match
  9357. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9358. (expand-file-name file))
  9359. (concat "file:"
  9360. (match-string 1 (expand-file-name file))))
  9361. (t (concat "file:" file)))))
  9362. (defvar ido-enter-matching-directory)
  9363. (defun org-iread-file-name (&rest args)
  9364. "Read-file-name using `ido-mode' speedup if available.
  9365. ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
  9366. See `read-file-name' for a description of parameters."
  9367. (org-without-partial-completion
  9368. (if (and org-completion-use-ido
  9369. (fboundp 'ido-read-file-name)
  9370. (org-bound-and-true-p ido-mode)
  9371. (listp (nth 1 args)))
  9372. (let ((ido-enter-matching-directory nil))
  9373. (apply #'ido-read-file-name args))
  9374. (apply #'read-file-name args))))
  9375. (defun org-completing-read (&rest args)
  9376. "Completing-read with SPACE being a normal character."
  9377. (let ((enable-recursive-minibuffers t)
  9378. (minibuffer-local-completion-map
  9379. (copy-keymap minibuffer-local-completion-map)))
  9380. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9381. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9382. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9383. 'org-time-stamp-inactive)
  9384. (apply #'completing-read args)))
  9385. (define-obsolete-function-alias
  9386. 'org-completing-read-no-i 'completing-read "Org 9.0")
  9387. (define-obsolete-function-alias
  9388. 'org-icompleting-read 'completing-read "Org 9.0")
  9389. ;;; Opening/following a link
  9390. (defvar org-link-search-failed nil)
  9391. (defvar org-open-link-functions nil
  9392. "Hook for functions finding a plain text link.
  9393. These functions must take a single argument, the link content.
  9394. They will be called for links that look like [[link text][description]]
  9395. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9396. like a filename (e.g. \"./blue.png\").
  9397. These functions will be called *before* Org attempts to resolve the
  9398. link by doing text searches in the current buffer - so if you want a
  9399. link \"[[target]]\" to still find \"<<target>>\", your function should
  9400. handle this as a special case.
  9401. When the function does handle the link, it must return a non-nil value.
  9402. If it decides that it is not responsible for this link, it must return
  9403. nil to indicate that that Org-mode can continue with other options
  9404. like exact and fuzzy text search.")
  9405. (defun org-next-link (&optional search-backward)
  9406. "Move forward to the next link.
  9407. If the link is in hidden text, expose it."
  9408. (interactive "P")
  9409. (when (and org-link-search-failed (eq this-command last-command))
  9410. (goto-char (point-min))
  9411. (message "Link search wrapped back to beginning of buffer"))
  9412. (setq org-link-search-failed nil)
  9413. (let* ((pos (point))
  9414. (ct (org-context))
  9415. (a (assoc :link ct))
  9416. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9417. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9418. ((looking-at org-any-link-re)
  9419. ;; Don't stay stuck at link without an org-link face
  9420. (forward-char (if search-backward -1 1))))
  9421. (if (funcall srch-fun org-any-link-re nil t)
  9422. (progn
  9423. (goto-char (match-beginning 0))
  9424. (when (outline-invisible-p) (org-show-context)))
  9425. (goto-char pos)
  9426. (setq org-link-search-failed t)
  9427. (message "No further link found"))))
  9428. (defun org-previous-link ()
  9429. "Move backward to the previous link.
  9430. If the link is in hidden text, expose it."
  9431. (interactive)
  9432. (funcall 'org-next-link t))
  9433. (defun org-translate-link (s)
  9434. "Translate a link string if a translation function has been defined."
  9435. (with-temp-buffer
  9436. (insert (org-trim s))
  9437. (org-trim (org-element-interpret-data (org-element-context)))))
  9438. (defun org-translate-link-from-planner (type path)
  9439. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9440. This is still an experimental function, your mileage may vary."
  9441. (cond
  9442. ((member type '("http" "https" "news" "ftp"))
  9443. ;; standard Internet links are the same.
  9444. nil)
  9445. ((and (equal type "irc") (string-match "^//" path))
  9446. ;; Planner has two / at the beginning of an irc link, we have 1.
  9447. ;; We should have zero, actually....
  9448. (setq path (substring path 1)))
  9449. ((and (equal type "lisp") (string-match "^/" path))
  9450. ;; Planner has a slash, we do not.
  9451. (setq type "elisp" path (substring path 1)))
  9452. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9453. ;; A typical message link. Planner has the id after the final slash,
  9454. ;; we separate it with a hash mark
  9455. (setq path (concat (match-string 1 path) "#"
  9456. (org-remove-angle-brackets (match-string 2 path))))))
  9457. (cons type path))
  9458. (defun org-find-file-at-mouse (ev)
  9459. "Open file link or URL at mouse."
  9460. (interactive "e")
  9461. (mouse-set-point ev)
  9462. (org-open-at-point 'in-emacs))
  9463. (defun org-open-at-mouse (ev)
  9464. "Open file link or URL at mouse.
  9465. See the docstring of `org-open-file' for details."
  9466. (interactive "e")
  9467. (mouse-set-point ev)
  9468. (when (eq major-mode 'org-agenda-mode)
  9469. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9470. (org-open-at-point))
  9471. (defvar org-window-config-before-follow-link nil
  9472. "The window configuration before following a link.
  9473. This is saved in case the need arises to restore it.")
  9474. ;;;###autoload
  9475. (defun org-open-at-point-global ()
  9476. "Follow a link like Org-mode does.
  9477. This command can be called in any mode to follow a link that has
  9478. Org-mode syntax."
  9479. (interactive)
  9480. (org-run-like-in-org-mode 'org-open-at-point))
  9481. ;;;###autoload
  9482. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9483. "Open a link in the string S, as if it was in Org-mode."
  9484. (interactive "sLink: \nP")
  9485. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9486. (with-temp-buffer
  9487. (let ((org-inhibit-startup (not reference-buffer)))
  9488. (org-mode)
  9489. (insert s)
  9490. (goto-char (point-min))
  9491. (when reference-buffer
  9492. (setq org-link-abbrev-alist-local
  9493. (with-current-buffer reference-buffer
  9494. org-link-abbrev-alist-local)))
  9495. (org-open-at-point arg reference-buffer)))))
  9496. (defvar org-open-at-point-functions nil
  9497. "Hook that is run when following a link at point.
  9498. Functions in this hook must return t if they identify and follow
  9499. a link at point. If they don't find anything interesting at point,
  9500. they must return nil.")
  9501. (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
  9502. (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
  9503. (defun org-open-at-point (&optional arg reference-buffer)
  9504. "Open link, timestamp, footnote or tags at point.
  9505. When point is on a link, follow it. Normally, files will be
  9506. opened by an appropriate application. If the optional prefix
  9507. argument ARG is non-nil, Emacs will visit the file. With
  9508. a double prefix argument, try to open outside of Emacs, in the
  9509. application the system uses for this file type.
  9510. When point is on a timestamp, open the agenda at the day
  9511. specified.
  9512. When point is a footnote definition, move to the first reference
  9513. found. If it is on a reference, move to the associated
  9514. definition.
  9515. When point is on a headline, display a list of every link in the
  9516. entry, so it is possible to pick one, or all, of them. If point
  9517. is on a tag, call `org-tags-view' instead.
  9518. When optional argument REFERENCE-BUFFER is non-nil, it should
  9519. specify a buffer from where the link search should happen. This
  9520. is used internally by `org-open-link-from-string'.
  9521. On top of syntactically correct links, this function will open
  9522. the link at point in comments or comment blocks and the first
  9523. link in a property drawer line."
  9524. (interactive "P")
  9525. ;; On a code block, open block's results.
  9526. (unless (call-interactively 'org-babel-open-src-block-result)
  9527. (org-load-modules-maybe)
  9528. (setq org-window-config-before-follow-link (current-window-configuration))
  9529. (org-remove-occur-highlights nil nil t)
  9530. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9531. (let* ((context
  9532. ;; Only consider supported types, even if they are not
  9533. ;; the closest one.
  9534. (org-element-lineage
  9535. (org-element-context)
  9536. '(clock comment comment-block footnote-definition
  9537. footnote-reference headline inlinetask keyword link
  9538. node-property timestamp)
  9539. t))
  9540. (type (org-element-type context))
  9541. (value (org-element-property :value context)))
  9542. (cond
  9543. ((not context) (user-error "No link found"))
  9544. ;; Exception: open timestamps and links in properties
  9545. ;; drawers, keywords and comments.
  9546. ((memq type '(comment comment-block keyword node-property))
  9547. (cond ((org-in-regexp org-any-link-re)
  9548. (org-open-link-from-string (match-string-no-properties 0)))
  9549. ((or (org-in-regexp org-ts-regexp-both nil t)
  9550. (org-in-regexp org-tsr-regexp-both nil t))
  9551. (org-follow-timestamp-link))
  9552. (t (user-error "No link found"))))
  9553. ;; On a headline or an inlinetask, but not on a timestamp,
  9554. ;; a link, a footnote reference or on tags.
  9555. ((and (memq type '(headline inlinetask))
  9556. ;; Not on tags.
  9557. (progn (save-excursion (beginning-of-line)
  9558. (looking-at org-complex-heading-regexp))
  9559. (or (not (match-beginning 5))
  9560. (< (point) (match-beginning 5)))))
  9561. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9562. (links (car data))
  9563. (links-end (cdr data)))
  9564. (if links
  9565. (dolist (link (if (stringp links) (list links) links))
  9566. (search-forward link nil links-end)
  9567. (goto-char (match-beginning 0))
  9568. (org-open-at-point))
  9569. (require 'org-attach)
  9570. (org-attach-reveal 'if-exists))))
  9571. ;; On a clock line, make sure point is on the timestamp
  9572. ;; before opening it.
  9573. ((and (eq type 'clock)
  9574. value
  9575. (>= (point) (org-element-property :begin value))
  9576. (<= (point) (org-element-property :end value)))
  9577. (org-follow-timestamp-link))
  9578. ;; Do nothing on white spaces after an object.
  9579. ((>= (point)
  9580. (save-excursion
  9581. (goto-char (org-element-property :end context))
  9582. (skip-chars-backward " \t")
  9583. (point)))
  9584. (user-error "No link found"))
  9585. ((eq type 'timestamp) (org-follow-timestamp-link))
  9586. ;; On tags within a headline or an inlinetask.
  9587. ((and (memq type '(headline inlinetask))
  9588. (progn (save-excursion (beginning-of-line)
  9589. (looking-at org-complex-heading-regexp))
  9590. (and (match-beginning 5)
  9591. (>= (point) (match-beginning 5)))))
  9592. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9593. ((eq type 'link)
  9594. ;; When link is located within the description of another
  9595. ;; link (e.g., an inline image), always open the parent
  9596. ;; link.
  9597. (let*((link (let ((up (org-element-property :parent context)))
  9598. (if (eq (org-element-type up) 'link) up context)))
  9599. (type (org-element-property :type link))
  9600. (path (org-link-unescape (org-element-property :path link))))
  9601. ;; Switch back to REFERENCE-BUFFER needed when called in
  9602. ;; a temporary buffer through `org-open-link-from-string'.
  9603. (with-current-buffer (or reference-buffer (current-buffer))
  9604. (cond
  9605. ((equal type "file")
  9606. (if (string-match "[*?{]" (file-name-nondirectory path))
  9607. (dired path)
  9608. ;; Look into `org-link-protocols' in order to find
  9609. ;; a DEDICATED-FUNCTION to open file. The function
  9610. ;; will be applied on raw link instead of parsed
  9611. ;; link due to the limitation in `org-add-link-type'
  9612. ;; ("open" function called with a single argument).
  9613. ;; If no such function is found, fallback to
  9614. ;; `org-open-file'.
  9615. ;;
  9616. ;; Note : "file+emacs" and "file+sys" types are
  9617. ;; hard-coded in order to escape the previous
  9618. ;; limitation.
  9619. (let* ((option (org-element-property :search-option link))
  9620. (app (org-element-property :application link))
  9621. (dedicated-function
  9622. (nth 1 (assoc app org-link-protocols))))
  9623. (if dedicated-function
  9624. (funcall dedicated-function
  9625. (concat path
  9626. (and option (concat "::" option))))
  9627. (apply #'org-open-file
  9628. path
  9629. (cond (arg)
  9630. ((equal app "emacs") 'emacs)
  9631. ((equal app "sys") 'system))
  9632. (cond ((not option) nil)
  9633. ((org-string-match-p "\\`[0-9]+\\'" option)
  9634. (list (string-to-number option)))
  9635. (t (list nil
  9636. (org-link-unescape option)))))))))
  9637. ((assoc type org-link-protocols)
  9638. (funcall (nth 1 (assoc type org-link-protocols)) path))
  9639. ((equal type "help")
  9640. (let ((f-or-v (intern path)))
  9641. (cond ((fboundp f-or-v) (describe-function f-or-v))
  9642. ((boundp f-or-v) (describe-variable f-or-v))
  9643. (t (error "Not a known function or variable")))))
  9644. ((member type '("http" "https" "ftp" "mailto" "news"))
  9645. (browse-url (org-link-escape-browser (concat type ":" path))))
  9646. ((equal type "doi")
  9647. (browse-url
  9648. (org-link-escape-browser (concat org-doi-server-url path))))
  9649. ((equal type "message") (browse-url (concat type ":" path)))
  9650. ((equal type "shell")
  9651. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9652. (cmd path))
  9653. (if (or (and (org-string-nw-p
  9654. org-confirm-shell-link-not-regexp)
  9655. (string-match
  9656. org-confirm-shell-link-not-regexp cmd))
  9657. (not org-confirm-shell-link-function)
  9658. (funcall org-confirm-shell-link-function
  9659. (format "Execute \"%s\" in shell? "
  9660. (org-add-props cmd nil
  9661. 'face 'org-warning))))
  9662. (progn
  9663. (message "Executing %s" cmd)
  9664. (shell-command cmd buf)
  9665. (when (featurep 'midnight)
  9666. (setq clean-buffer-list-kill-buffer-names
  9667. (cons (buffer-name buf)
  9668. clean-buffer-list-kill-buffer-names))))
  9669. (user-error "Abort"))))
  9670. ((equal type "elisp")
  9671. (let ((cmd path))
  9672. (if (or (and (org-string-nw-p
  9673. org-confirm-elisp-link-not-regexp)
  9674. (org-string-match-p
  9675. org-confirm-elisp-link-not-regexp cmd))
  9676. (not org-confirm-elisp-link-function)
  9677. (funcall org-confirm-elisp-link-function
  9678. (format "Execute \"%s\" as elisp? "
  9679. (org-add-props cmd nil
  9680. 'face 'org-warning))))
  9681. (message "%s => %s" cmd
  9682. (if (eq (string-to-char cmd) ?\()
  9683. (eval (read cmd))
  9684. (call-interactively (read cmd))))
  9685. (user-error "Abort"))))
  9686. ((equal type "id")
  9687. (require 'org-id)
  9688. (funcall (nth 1 (assoc "id" org-link-protocols)) path))
  9689. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9690. (unless (run-hook-with-args-until-success
  9691. 'org-open-link-functions path)
  9692. (if (not arg) (org-mark-ring-push)
  9693. (switch-to-buffer-other-window
  9694. (org-get-buffer-for-internal-link (current-buffer))))
  9695. (let ((destination
  9696. (org-with-wide-buffer
  9697. (if (equal type "radio")
  9698. (org-search-radio-target
  9699. (org-element-property :path link))
  9700. (org-link-search
  9701. (if (member type '("custom-id" "coderef"))
  9702. (org-element-property :raw-link link)
  9703. path)
  9704. ;; Prevent fuzzy links from matching
  9705. ;; themselves.
  9706. (and (equal type "fuzzy")
  9707. (+ 2 (org-element-property :begin link)))))
  9708. (point))))
  9709. (unless (and (<= (point-min) destination)
  9710. (>= (point-max) destination))
  9711. (widen))
  9712. (goto-char destination))))
  9713. (t (browse-url-at-point))))))
  9714. ;; On a footnote reference or at a footnote definition's label.
  9715. ((or (eq type 'footnote-reference)
  9716. (and (eq type 'footnote-definition)
  9717. (save-excursion
  9718. ;; Do not validate action when point is on the
  9719. ;; spaces right after the footnote label, in
  9720. ;; order to be on par with behaviour on links.
  9721. (skip-chars-forward " \t")
  9722. (let ((begin
  9723. (org-element-property :contents-begin context)))
  9724. (if begin (< (point) begin)
  9725. (= (org-element-property :post-affiliated context)
  9726. (line-beginning-position)))))))
  9727. (org-footnote-action))
  9728. (t (user-error "No link found")))))
  9729. (run-hook-with-args 'org-follow-link-hook)))
  9730. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9731. "Offer links in the current entry and return the selected link.
  9732. If there is only one link, return it.
  9733. If NTH is an integer, return the NTH link found.
  9734. If ZERO is a string, check also this string for a link, and if
  9735. there is one, return it."
  9736. (with-current-buffer buffer
  9737. (save-excursion
  9738. (save-restriction
  9739. (widen)
  9740. (goto-char marker)
  9741. (let ((cnt ?0)
  9742. have-zero end links link c)
  9743. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9744. (push (match-string 0 zero) links)
  9745. (setq cnt (1- cnt) have-zero t))
  9746. (save-excursion
  9747. (org-back-to-heading t)
  9748. (setq end (save-excursion (outline-next-heading) (point)))
  9749. (while (re-search-forward org-any-link-re end t)
  9750. (push (match-string 0) links))
  9751. (setq links (org-uniquify (reverse links))))
  9752. (cond
  9753. ((null links)
  9754. (message "No links"))
  9755. ((equal (length links) 1)
  9756. (setq link (car links)))
  9757. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9758. (setq link (nth (if have-zero nth (1- nth)) links)))
  9759. (t ; we have to select a link
  9760. (save-excursion
  9761. (save-window-excursion
  9762. (delete-other-windows)
  9763. (with-output-to-temp-buffer "*Select Link*"
  9764. (mapc (lambda (l)
  9765. (if (not (string-match org-bracket-link-regexp l))
  9766. (princ (format "[%c] %s\n" (incf cnt)
  9767. (org-remove-angle-brackets l)))
  9768. (if (match-end 3)
  9769. (princ (format "[%c] %s (%s)\n" (incf cnt)
  9770. (match-string 3 l) (match-string 1 l)))
  9771. (princ (format "[%c] %s\n" (incf cnt)
  9772. (match-string 1 l))))))
  9773. links))
  9774. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9775. (message "Select link to open, RET to open all:")
  9776. (setq c (read-char-exclusive))
  9777. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9778. (when (equal c ?q) (user-error "Abort"))
  9779. (if (equal c ?\C-m)
  9780. (setq link links)
  9781. (setq nth (- c ?0))
  9782. (when have-zero (setq nth (1+ nth)))
  9783. (unless (and (integerp nth) (>= (length links) nth))
  9784. (user-error "Invalid link selection"))
  9785. (setq link (nth (1- nth) links)))))
  9786. (cons link end))))))
  9787. ;; TODO: These functions are deprecated since `org-open-at-point'
  9788. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9789. (defun org-open-file-with-system (path)
  9790. "Open file at PATH using the system way of opening it."
  9791. (org-open-file path 'system))
  9792. (defun org-open-file-with-emacs (path)
  9793. "Open file at PATH in Emacs."
  9794. (org-open-file path 'emacs))
  9795. ;;; File search
  9796. (defvar org-create-file-search-functions nil
  9797. "List of functions to construct the right search string for a file link.
  9798. These functions are called in turn with point at the location to
  9799. which the link should point.
  9800. A function in the hook should first test if it would like to
  9801. handle this file type, for example by checking the `major-mode'
  9802. or the file extension. If it decides not to handle this file, it
  9803. should just return nil to give other functions a chance. If it
  9804. does handle the file, it must return the search string to be used
  9805. when following the link. The search string will be part of the
  9806. file link, given after a double colon, and `org-open-at-point'
  9807. will automatically search for it. If special measures must be
  9808. taken to make the search successful, another function should be
  9809. added to the companion hook `org-execute-file-search-functions',
  9810. which see.
  9811. A function in this hook may also use `setq' to set the variable
  9812. `description' to provide a suggestion for the descriptive text to
  9813. be used for this link when it gets inserted into an Org-mode
  9814. buffer with \\[org-insert-link].")
  9815. (defvar org-execute-file-search-functions nil
  9816. "List of functions to execute a file search triggered by a link.
  9817. Functions added to this hook must accept a single argument, the
  9818. search string that was part of the file link, the part after the
  9819. double colon. The function must first check if it would like to
  9820. handle this search, for example by checking the `major-mode' or
  9821. the file extension. If it decides not to handle this search, it
  9822. should just return nil to give other functions a chance. If it
  9823. does handle the search, it must return a non-nil value to keep
  9824. other functions from trying.
  9825. Each function can access the current prefix argument through the
  9826. variable `current-prefix-arg'. Note that a single prefix is used
  9827. to force opening a link in Emacs, so it may be good to only use a
  9828. numeric or double prefix to guide the search function.
  9829. In case this is needed, a function in this hook can also restore
  9830. the window configuration before `org-open-at-point' was called using:
  9831. (set-window-configuration org-window-config-before-follow-link)")
  9832. (defun org-search-radio-target (target)
  9833. "Search a radio target matching TARGET in current buffer.
  9834. White spaces are not significant."
  9835. (let ((re (format "<<<%s>>>"
  9836. (mapconcat #'regexp-quote
  9837. (org-split-string target "[ \t\n]+")
  9838. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9839. (origin (point)))
  9840. (goto-char (point-min))
  9841. (catch :radio-match
  9842. (while (re-search-forward re nil t)
  9843. (backward-char)
  9844. (let ((object (org-element-context)))
  9845. (when (eq (org-element-type object) 'radio-target)
  9846. (goto-char (org-element-property :begin object))
  9847. (org-show-context 'link-search)
  9848. (throw :radio-match nil))))
  9849. (goto-char origin)
  9850. (user-error "No match for radio target: %s" target))))
  9851. (defun org-link-search (s &optional avoid-pos stealth)
  9852. "Search for a search string S.
  9853. If S starts with \"#\", it triggers a custom ID search.
  9854. If S is enclosed within parenthesis, it initiates a coderef
  9855. search.
  9856. If S is surrounded by forward slashes, it is interpreted as
  9857. a regular expression. In Org mode files, this will create an
  9858. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9859. to list matches. If the current buffer is in `dired-mode', grep
  9860. will be used to search in all files.
  9861. When AVOID-POS is given, ignore matches near that position.
  9862. When optional argument STEALTH is non-nil, do not modify
  9863. visibility around point, thus ignoring `org-show-context-detail'
  9864. variable.
  9865. Search is case-insensitive and ignores white spaces. Return type
  9866. of matched result, with is either `dedicated' or `fuzzy'."
  9867. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9868. (let* ((case-fold-search t)
  9869. (origin (point))
  9870. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9871. (words (org-split-string s "[ \t\n]+"))
  9872. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9873. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9874. type)
  9875. (cond
  9876. ;; Check if there are any special search functions.
  9877. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9878. ((eq (string-to-char s) ?#)
  9879. ;; Look for a custom ID S if S starts with "#".
  9880. (let* ((id (substring normalized 1))
  9881. (match (org-find-property "CUSTOM_ID" id)))
  9882. (if match (progn (goto-char match) (setf type 'dedicated))
  9883. (error "No match for custom ID: %s" id))))
  9884. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9885. ;; Look for coderef targets if S is enclosed within parenthesis.
  9886. (let ((coderef (match-string-no-properties 1 normalized))
  9887. (re (substring s-single-re 1 -1)))
  9888. (goto-char (point-min))
  9889. (catch :coderef-match
  9890. (while (re-search-forward re nil t)
  9891. (let ((element (org-element-at-point)))
  9892. (when (and (memq (org-element-type element)
  9893. '(example-block src-block))
  9894. ;; Build proper regexp according to current
  9895. ;; block's label format.
  9896. (let ((label-fmt
  9897. (regexp-quote
  9898. (or (org-element-property :label-fmt element)
  9899. org-coderef-label-format))))
  9900. (save-excursion
  9901. (beginning-of-line)
  9902. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9903. (format label-fmt coderef))))))
  9904. (setq type 'dedicated)
  9905. (goto-char (match-beginning 1))
  9906. (throw :coderef-match nil))))
  9907. (goto-char origin)
  9908. (error "No match for coderef: %s" coderef))))
  9909. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9910. ;; Look for a regular expression.
  9911. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9912. (match-string 1 s)))
  9913. ;; Fuzzy links.
  9914. (t
  9915. (let ((starred (eq (string-to-char normalized) ?*)))
  9916. (cond
  9917. ;; Look for targets, only if not in a headline search.
  9918. ((and (not starred)
  9919. (let ((target (format "<<%s>>" s-multi-re)))
  9920. (catch :target-match
  9921. (goto-char (point-min))
  9922. (while (re-search-forward target nil t)
  9923. (backward-char)
  9924. (let ((context (org-element-context)))
  9925. (when (eq (org-element-type context) 'target)
  9926. (setq type 'dedicated)
  9927. (goto-char (org-element-property :begin context))
  9928. (throw :target-match t))))
  9929. nil))))
  9930. ;; Look for elements named after S, only if not in a headline
  9931. ;; search.
  9932. ((and (not starred)
  9933. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9934. (catch :name-match
  9935. (goto-char (point-min))
  9936. (while (re-search-forward name nil t)
  9937. (let ((element (org-element-at-point)))
  9938. (when (equal (org-split-string
  9939. (org-element-property :name element)
  9940. "[ \t]+")
  9941. words)
  9942. (setq type 'dedicated)
  9943. (beginning-of-line)
  9944. (throw :name-match t))))
  9945. nil))))
  9946. ;; Regular text search. Prefer headlines in Org mode
  9947. ;; buffers.
  9948. ((and (derived-mode-p 'org-mode)
  9949. (let* ((wspace "[ \t]")
  9950. (wspaceopt (concat wspace "*"))
  9951. (cookie (concat "\\(?:"
  9952. wspaceopt
  9953. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  9954. wspaceopt
  9955. "\\)"))
  9956. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  9957. (re (concat
  9958. org-outline-regexp-bol
  9959. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  9960. "\\(?:\\[#.\\][ \t]+\\)?"
  9961. "\\(?:" org-comment-string "[ \t]+\\)?"
  9962. sep "?"
  9963. (let ((title (mapconcat #'regexp-quote
  9964. words
  9965. sep)))
  9966. (if starred (substring title 1) title))
  9967. sep "?"
  9968. (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
  9969. "[ \t]*$")))
  9970. (goto-char (point-min))
  9971. (re-search-forward re nil t)))
  9972. (goto-char (match-beginning 0))
  9973. (setq type 'dedicated))
  9974. ;; Offer to create non-existent headline depending on
  9975. ;; `org-link-search-must-match-exact-headline'.
  9976. ((and (derived-mode-p 'org-mode)
  9977. (not org-link-search-inhibit-query)
  9978. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9979. (yes-or-no-p "No match - create this as a new heading? "))
  9980. (goto-char (point-max))
  9981. (unless (bolp) (newline))
  9982. (org-insert-heading nil t t)
  9983. (insert s "\n")
  9984. (beginning-of-line 0))
  9985. ;; Only headlines are looked after. No need to process
  9986. ;; further: throw an error.
  9987. ((and (derived-mode-p 'org-mode)
  9988. (or starred org-link-search-must-match-exact-headline))
  9989. (goto-char origin)
  9990. (error "No match for fuzzy expression: %s" normalized))
  9991. ;; Regular text search.
  9992. ((catch :fuzzy-match
  9993. (goto-char (point-min))
  9994. (while (re-search-forward s-multi-re nil t)
  9995. ;; Skip match if it contains AVOID-POS or it is included
  9996. ;; in a link with a description but outside the
  9997. ;; description.
  9998. (unless (or (and avoid-pos
  9999. (<= (match-beginning 0) avoid-pos)
  10000. (> (match-end 0) avoid-pos))
  10001. (and (save-match-data
  10002. (org-in-regexp org-bracket-link-regexp))
  10003. (match-beginning 3)
  10004. (or (> (match-beginning 3) (point))
  10005. (<= (match-end 3) (point)))
  10006. (org-element-lineage
  10007. (save-match-data (org-element-context))
  10008. '(link) t)))
  10009. (goto-char (match-beginning 0))
  10010. (setq type 'fuzzy)
  10011. (throw :fuzzy-match t)))
  10012. nil))
  10013. ;; All failed. Throw an error.
  10014. (t (goto-char origin)
  10015. (error "No match for fuzzy expression: %s" normalized))))))
  10016. ;; Disclose surroundings of match, if appropriate.
  10017. (when (and (derived-mode-p 'org-mode) (not stealth))
  10018. (org-show-context 'link-search))
  10019. type))
  10020. (defun org-get-buffer-for-internal-link (buffer)
  10021. "Return a buffer to be used for displaying the link target of internal links."
  10022. (cond
  10023. ((not org-display-internal-link-with-indirect-buffer)
  10024. buffer)
  10025. ((string-match "(Clone)$" (buffer-name buffer))
  10026. (message "Buffer is already a clone, not making another one")
  10027. ;; we also do not modify visibility in this case
  10028. buffer)
  10029. (t ; make a new indirect buffer for displaying the link
  10030. (let* ((bn (buffer-name buffer))
  10031. (ibn (concat bn "(Clone)"))
  10032. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10033. (with-current-buffer ib (org-overview))
  10034. ib))))
  10035. (defun org-do-occur (regexp &optional cleanup)
  10036. "Call the Emacs command `occur'.
  10037. If CLEANUP is non-nil, remove the printout of the regular expression
  10038. in the *Occur* buffer. This is useful if the regex is long and not useful
  10039. to read."
  10040. (occur regexp)
  10041. (when cleanup
  10042. (let ((cwin (selected-window)) win beg end)
  10043. (when (setq win (get-buffer-window "*Occur*"))
  10044. (select-window win))
  10045. (goto-char (point-min))
  10046. (when (re-search-forward "match[a-z]+" nil t)
  10047. (setq beg (match-end 0))
  10048. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10049. (setq end (1- (match-beginning 0)))))
  10050. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10051. (goto-char (point-min))
  10052. (select-window cwin))))
  10053. ;;; The mark ring for links jumps
  10054. (defvar org-mark-ring nil
  10055. "Mark ring for positions before jumps in Org-mode.")
  10056. (defvar org-mark-ring-last-goto nil
  10057. "Last position in the mark ring used to go back.")
  10058. ;; Fill and close the ring
  10059. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10060. (loop for i from 1 to org-mark-ring-length do
  10061. (push (make-marker) org-mark-ring))
  10062. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10063. org-mark-ring)
  10064. (defun org-mark-ring-push (&optional pos buffer)
  10065. "Put the current position or POS into the mark ring and rotate it."
  10066. (interactive)
  10067. (setq pos (or pos (point)))
  10068. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10069. (move-marker (car org-mark-ring)
  10070. (or pos (point))
  10071. (or buffer (current-buffer)))
  10072. (message "%s"
  10073. (substitute-command-keys
  10074. "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
  10075. (defun org-mark-ring-goto (&optional n)
  10076. "Jump to the previous position in the mark ring.
  10077. With prefix arg N, jump back that many stored positions. When
  10078. called several times in succession, walk through the entire ring.
  10079. Org-mode commands jumping to a different position in the current file,
  10080. or to another Org-mode file, automatically push the old position
  10081. onto the ring."
  10082. (interactive "p")
  10083. (let (p m)
  10084. (if (eq last-command this-command)
  10085. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10086. (setq p org-mark-ring))
  10087. (setq org-mark-ring-last-goto p)
  10088. (setq m (car p))
  10089. (org-pop-to-buffer-same-window (marker-buffer m))
  10090. (goto-char m)
  10091. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10092. ;;; TODO: Use string-remove-prefix and -suffix once we only support
  10093. ;;; Emacs 24.4+
  10094. (defun org-remove-angle-brackets (s)
  10095. (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
  10096. (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
  10097. s)
  10098. (defun org-add-angle-brackets (s)
  10099. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10100. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10101. s)
  10102. (defun org-remove-double-quotes (s)
  10103. (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
  10104. (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
  10105. s)
  10106. ;;; Following specific links
  10107. (defun org-follow-timestamp-link ()
  10108. "Open an agenda view for the time-stamp date/range at point."
  10109. (cond
  10110. ((org-at-date-range-p t)
  10111. (let ((org-agenda-start-on-weekday)
  10112. (t1 (match-string 1))
  10113. (t2 (match-string 2)) tt1 tt2)
  10114. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10115. tt2 (time-to-days (org-time-string-to-time t2)))
  10116. (let ((org-agenda-buffer-tmp-name
  10117. (format "*Org Agenda(a:%s)"
  10118. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10119. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10120. ((org-at-timestamp-p t)
  10121. (let ((org-agenda-buffer-tmp-name
  10122. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10123. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10124. (substring (match-string 1) 0 10)))
  10125. 1)))
  10126. (t (error "This should not happen"))))
  10127. ;;; Following file links
  10128. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10129. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10130. (declare-function mailcap-mime-info
  10131. "mailcap" (string &optional request no-decode))
  10132. (defvar org-wait nil)
  10133. (defun org-open-file (path &optional in-emacs line search)
  10134. "Open the file at PATH.
  10135. First, this expands any special file name abbreviations. Then the
  10136. configuration variable `org-file-apps' is checked if it contains an
  10137. entry for this file type, and if yes, the corresponding command is launched.
  10138. If no application is found, Emacs simply visits the file.
  10139. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10140. With a double \\[universal-argument] \\[universal-argument] \
  10141. prefix arg, Org tries to avoid opening in Emacs
  10142. and to use an external application to visit the file.
  10143. Optional LINE specifies a line to go to, optional SEARCH a string
  10144. to search for. If LINE or SEARCH is given, the file will be
  10145. opened in Emacs, unless an entry from org-file-apps that makes
  10146. use of groups in a regexp matches.
  10147. If you want to change the way frames are used when following a
  10148. link, please customize `org-link-frame-setup'.
  10149. If the file does not exist, an error is thrown."
  10150. (let* ((file (if (equal path "")
  10151. buffer-file-name
  10152. (substitute-in-file-name (expand-file-name path))))
  10153. (file-apps (append org-file-apps (org-default-apps)))
  10154. (apps (cl-remove-if
  10155. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10156. (apps-dlink (cl-remove-if-not
  10157. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10158. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10159. (dirp (unless remp (file-directory-p file)))
  10160. (file (if (and dirp org-open-directory-means-index-dot-org)
  10161. (concat (file-name-as-directory file) "index.org")
  10162. file))
  10163. (a-m-a-p (assq 'auto-mode apps))
  10164. (dfile (downcase file))
  10165. ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
  10166. (link (cond ((and (eq line nil)
  10167. (eq search nil))
  10168. file)
  10169. (line
  10170. (concat file "::" (number-to-string line)))
  10171. (search
  10172. (concat file "::" search))))
  10173. (dlink (downcase link))
  10174. (old-buffer (current-buffer))
  10175. (old-pos (point))
  10176. (old-mode major-mode)
  10177. ext cmd link-match-data)
  10178. (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
  10179. (setq ext (match-string 1 dfile))
  10180. (when (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
  10181. (setq ext (match-string 1 dfile))))
  10182. (cond
  10183. ((member in-emacs '((16) system))
  10184. (setq cmd (cdr (assoc 'system apps))))
  10185. (in-emacs (setq cmd 'emacs))
  10186. (t
  10187. (setq cmd (or (and remp (cdr (assoc 'remote apps)))
  10188. (and dirp (cdr (assoc 'directory apps)))
  10189. ; first, try matching against apps-dlink
  10190. ; if we get a match here, store the match data for later
  10191. (let ((match (assoc-default dlink apps-dlink
  10192. 'string-match)))
  10193. (if match
  10194. (progn (setq link-match-data (match-data))
  10195. match)
  10196. (progn (setq in-emacs (or in-emacs line search))
  10197. nil))) ; if we have no match in apps-dlink,
  10198. ; always open the file in emacs if line or search
  10199. ; is given (for backwards compatibility)
  10200. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10201. 'string-match)
  10202. (cdr (assoc ext apps))
  10203. (cdr (assoc t apps))))))
  10204. (when (eq cmd 'system)
  10205. (setq cmd (cdr (assoc 'system apps))))
  10206. (when (eq cmd 'default)
  10207. (setq cmd (cdr (assoc t apps))))
  10208. (when (eq cmd 'mailcap)
  10209. (require 'mailcap)
  10210. (mailcap-parse-mailcaps)
  10211. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10212. (command (mailcap-mime-info mime-type)))
  10213. (if (stringp command)
  10214. (setq cmd command)
  10215. (setq cmd 'emacs))))
  10216. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10217. (not (file-exists-p file))
  10218. (not org-open-non-existing-files))
  10219. (user-error "No such file: %s" file))
  10220. (cond
  10221. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10222. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10223. (while (string-match "['\"]%s['\"]" cmd)
  10224. (setq cmd (replace-match "%s" t t cmd)))
  10225. (while (string-match "%s" cmd)
  10226. (setq cmd (replace-match
  10227. (save-match-data
  10228. (shell-quote-argument
  10229. (convert-standard-filename file)))
  10230. t t cmd)))
  10231. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10232. (save-match-data
  10233. (let ((match-index 1)
  10234. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10235. (set-match-data link-match-data)
  10236. (while (<= match-index number-of-groups)
  10237. (let ((regex (concat "%" (number-to-string match-index)))
  10238. (replace-with (match-string match-index dlink)))
  10239. (while (string-match regex cmd)
  10240. (setq cmd (replace-match replace-with t t cmd))))
  10241. (setq match-index (+ match-index 1)))))
  10242. (save-window-excursion
  10243. (message "Running %s...done" cmd)
  10244. (start-process-shell-command cmd nil cmd)
  10245. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10246. ((or (stringp cmd)
  10247. (eq cmd 'emacs))
  10248. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10249. (widen)
  10250. (if line (progn (org-goto-line line)
  10251. (when (derived-mode-p 'org-mode)
  10252. (org-reveal)))
  10253. (when search (org-link-search search))))
  10254. ((consp cmd)
  10255. (save-match-data
  10256. (set-match-data link-match-data)
  10257. (eval cmd `((file . ,(convert-standard-filename file))))))
  10258. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10259. (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
  10260. (or (not (equal old-buffer (current-buffer)))
  10261. (not (equal old-pos (point))))
  10262. (org-mark-ring-push old-pos old-buffer))))
  10263. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10264. "This function returns non-nil if `entry' uses a regular
  10265. expression which should be matched against the whole link by
  10266. org-open-file.
  10267. It assumes that is the case when the entry uses a regular
  10268. expression which has at least one grouping construct and the
  10269. action is either a lisp form or a command string containing
  10270. `%1', i.e. using at least one subexpression match as a
  10271. parameter."
  10272. (let ((selector (car entry))
  10273. (action (cdr entry)))
  10274. (if (stringp selector)
  10275. (and (> (regexp-opt-depth selector) 0)
  10276. (or (and (stringp action)
  10277. (string-match "%[0-9]" action))
  10278. (consp action)))
  10279. nil)))
  10280. (defun org-default-apps ()
  10281. "Return the default applications for this operating system."
  10282. (cond
  10283. ((eq system-type 'darwin)
  10284. org-file-apps-defaults-macosx)
  10285. ((eq system-type 'windows-nt)
  10286. org-file-apps-defaults-windowsnt)
  10287. (t org-file-apps-defaults-gnu)))
  10288. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10289. "Convert extensions to regular expressions in the cars of LIST.
  10290. Also, weed out any non-string entries, because the return value is used
  10291. only for regexp matching.
  10292. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10293. point to the symbol `emacs', indicating that the file should
  10294. be opened in Emacs."
  10295. (append
  10296. (delq nil
  10297. (mapcar (lambda (x)
  10298. (unless (not (stringp (car x)))
  10299. (if (string-match "\\W" (car x))
  10300. x
  10301. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10302. list))
  10303. (when add-auto-mode
  10304. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10305. (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
  10306. (defun org-file-remote-p (file)
  10307. "Test whether FILE specifies a location on a remote system.
  10308. Return non-nil if the location is indeed remote.
  10309. For example, the filename \"/user@host:/foo\" specifies a location
  10310. on the system \"/user@host:\"."
  10311. (cond ((fboundp 'file-remote-p)
  10312. (file-remote-p file))
  10313. ((fboundp 'tramp-handle-file-remote-p)
  10314. (tramp-handle-file-remote-p file))
  10315. ((and (boundp 'ange-ftp-name-format)
  10316. (string-match (car ange-ftp-name-format) file))
  10317. t)))
  10318. ;;;; Refiling
  10319. (defun org-get-org-file ()
  10320. "Read a filename, with default directory `org-directory'."
  10321. (let ((default (or org-default-notes-file remember-data-file)))
  10322. (read-file-name (format "File name [%s]: " default)
  10323. (file-name-as-directory org-directory)
  10324. default)))
  10325. (defun org-notes-order-reversed-p ()
  10326. "Check if the current file should receive notes in reversed order."
  10327. (cond
  10328. ((not org-reverse-note-order) nil)
  10329. ((eq t org-reverse-note-order) t)
  10330. ((not (listp org-reverse-note-order)) nil)
  10331. (t (catch 'exit
  10332. (dolist (entry org-reverse-note-order)
  10333. (when (string-match (car entry) buffer-file-name)
  10334. (throw 'exit (cdr entry))))))))
  10335. (defvar org-refile-target-table nil
  10336. "The list of refile targets, created by `org-refile'.")
  10337. (defvar org-agenda-new-buffers nil
  10338. "Buffers created to visit agenda files.")
  10339. (defvar org-refile-cache nil
  10340. "Cache for refile targets.")
  10341. (defvar org-refile-markers nil
  10342. "All the markers used for caching refile locations.")
  10343. (defun org-refile-marker (pos)
  10344. "Get a new refile marker, but only if caching is in use."
  10345. (if (not org-refile-use-cache)
  10346. pos
  10347. (let ((m (make-marker)))
  10348. (move-marker m pos)
  10349. (push m org-refile-markers)
  10350. m)))
  10351. (defun org-refile-cache-clear ()
  10352. "Clear the refile cache and disable all the markers."
  10353. (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
  10354. (setq org-refile-markers nil)
  10355. (setq org-refile-cache nil)
  10356. (message "Refile cache has been cleared"))
  10357. (defun org-refile-cache-check-set (set)
  10358. "Check if all the markers in the cache still have live buffers."
  10359. (let (marker)
  10360. (catch 'exit
  10361. (while (and set (setq marker (nth 3 (pop set))))
  10362. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10363. (when (and marker (null (marker-buffer marker)))
  10364. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10365. (sit-for 3)
  10366. (throw 'exit nil)))
  10367. t)))
  10368. (defun org-refile-cache-put (set &rest identifiers)
  10369. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10370. (let* ((key (sha1 (prin1-to-string identifiers)))
  10371. (entry (assoc key org-refile-cache)))
  10372. (if entry
  10373. (setcdr entry set)
  10374. (push (cons key set) org-refile-cache))))
  10375. (defun org-refile-cache-get (&rest identifiers)
  10376. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10377. (cond
  10378. ((not org-refile-cache) nil)
  10379. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10380. (t
  10381. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10382. org-refile-cache))))
  10383. (and set (org-refile-cache-check-set set) set)))))
  10384. (defun org-refile-get-targets (&optional default-buffer excluded-entries)
  10385. "Produce a table with refile targets."
  10386. (let ((case-fold-search nil)
  10387. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10388. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10389. targets tgs txt re files desc descre fast-path-p level pos0)
  10390. (message "Getting targets...")
  10391. (with-current-buffer (or default-buffer (current-buffer))
  10392. (dolist (entry entries)
  10393. (setq files (car entry) desc (cdr entry))
  10394. (setq fast-path-p nil)
  10395. (cond
  10396. ((null files) (setq files (list (current-buffer))))
  10397. ((eq files 'org-agenda-files)
  10398. (setq files (org-agenda-files 'unrestricted)))
  10399. ((and (symbolp files) (fboundp files))
  10400. (setq files (funcall files)))
  10401. ((and (symbolp files) (boundp files))
  10402. (setq files (symbol-value files))))
  10403. (when (stringp files) (setq files (list files)))
  10404. (cond
  10405. ((eq (car desc) :tag)
  10406. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10407. ((eq (car desc) :todo)
  10408. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10409. ((eq (car desc) :regexp)
  10410. (setq descre (cdr desc)))
  10411. ((eq (car desc) :level)
  10412. (setq descre (concat "^\\*\\{" (number-to-string
  10413. (if org-odd-levels-only
  10414. (1- (* 2 (cdr desc)))
  10415. (cdr desc)))
  10416. "\\}[ \t]")))
  10417. ((eq (car desc) :maxlevel)
  10418. (setq fast-path-p t)
  10419. (setq descre (concat "^\\*\\{1," (number-to-string
  10420. (if org-odd-levels-only
  10421. (1- (* 2 (cdr desc)))
  10422. (cdr desc)))
  10423. "\\}[ \t]")))
  10424. (t (error "Bad refiling target description %s" desc)))
  10425. (dolist (f files)
  10426. (with-current-buffer
  10427. (if (bufferp f) f (org-get-agenda-file-buffer f))
  10428. (or
  10429. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10430. (progn
  10431. (when (bufferp f) (setq f (buffer-file-name
  10432. (buffer-base-buffer f))))
  10433. (setq f (and f (expand-file-name f)))
  10434. (when (eq org-refile-use-outline-path 'file)
  10435. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10436. (save-excursion
  10437. (save-restriction
  10438. (widen)
  10439. (goto-char (point-min))
  10440. (while (re-search-forward descre nil t)
  10441. (goto-char (setq pos0 (point-at-bol)))
  10442. (catch 'next
  10443. (when org-refile-target-verify-function
  10444. (save-match-data
  10445. (or (funcall org-refile-target-verify-function)
  10446. (throw 'next t))))
  10447. (when (and (looking-at org-complex-heading-regexp)
  10448. (not (member (match-string 4) excluded-entries))
  10449. (match-string 4))
  10450. (setq level (org-reduced-level
  10451. (- (match-end 1) (match-beginning 1)))
  10452. txt (org-link-display-format (match-string 4))
  10453. txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
  10454. re (format org-complex-heading-regexp-format
  10455. (regexp-quote (match-string 4))))
  10456. (when org-refile-use-outline-path
  10457. (setq txt (mapconcat
  10458. 'org-protect-slash
  10459. (append
  10460. (if (eq org-refile-use-outline-path
  10461. 'file)
  10462. (list (file-name-nondirectory
  10463. (buffer-file-name
  10464. (buffer-base-buffer))))
  10465. (when (eq org-refile-use-outline-path
  10466. 'full-file-path)
  10467. (list (buffer-file-name
  10468. (buffer-base-buffer)))))
  10469. (org-get-outline-path fast-path-p
  10470. level txt)
  10471. (list txt))
  10472. "/")))
  10473. (push (list txt f re (org-refile-marker (point)))
  10474. tgs)))
  10475. (when (= (point) pos0)
  10476. ;; verification function has not moved point
  10477. (goto-char (point-at-eol))))))))
  10478. (when org-refile-use-cache
  10479. (org-refile-cache-put tgs (buffer-file-name) descre))
  10480. (setq targets (append tgs targets))))))
  10481. (message "Getting targets...done")
  10482. (nreverse targets)))
  10483. (defun org-protect-slash (s)
  10484. (while (string-match "/" s)
  10485. (setq s (replace-match "\\" t t s)))
  10486. s)
  10487. (defvar org-olpa (make-vector 20 nil))
  10488. (defun org-get-outline-path (&optional fastp level heading)
  10489. "Return the outline path to the current entry, as a list.
  10490. The parameters FASTP, LEVEL, and HEADING are for use by a scanner
  10491. routine which makes outline path derivations for an entire file,
  10492. avoiding backtracing. Refile target collection makes use of that."
  10493. (if fastp
  10494. (progn
  10495. (when (> level 19)
  10496. (error "Outline path failure, more than 19 levels"))
  10497. (loop for i from level upto 19 do
  10498. (aset org-olpa i nil))
  10499. (prog1
  10500. (delq nil (append org-olpa nil))
  10501. (aset org-olpa level heading)))
  10502. (let (rtn case-fold-search)
  10503. (save-excursion
  10504. (save-restriction
  10505. (widen)
  10506. (while (org-up-heading-safe)
  10507. (when (looking-at org-complex-heading-regexp)
  10508. (push (org-trim
  10509. (replace-regexp-in-string
  10510. ;; Remove statistical/checkboxes cookies
  10511. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10512. (org-match-string-no-properties 4)))
  10513. rtn)))
  10514. rtn)))))
  10515. (defun org-format-outline-path (path &optional width prefix separator)
  10516. "Format the outline path PATH for display.
  10517. WIDTH is the maximum number of characters that is available.
  10518. PREFIX is a prefix to be included in the returned string,
  10519. such as the file name.
  10520. SEPARATOR is inserted between the different parts of the path,
  10521. the default is \"/\"."
  10522. (setq width (or width 79))
  10523. (setq path (delq nil path))
  10524. (unless (> width 0)
  10525. (user-error "Argument `width' must be positive"))
  10526. (setq separator (or separator "/"))
  10527. (let* ((org-odd-levels-only nil)
  10528. (fpath (concat
  10529. prefix (and prefix path separator)
  10530. (mapconcat
  10531. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10532. (loop for head in path
  10533. for n from 0
  10534. collect (org-add-props
  10535. head nil 'face
  10536. (nth (% n org-n-level-faces) org-level-faces)))
  10537. separator))))
  10538. (when (> (length fpath) width)
  10539. (if (< width 7)
  10540. ;; It's unlikely that `width' will be this small, but don't
  10541. ;; waste characters by adding ".." if it is.
  10542. (setq fpath (substring fpath 0 width))
  10543. (setf (substring fpath (- width 2)) "..")))
  10544. fpath))
  10545. (defun org-display-outline-path (&optional file current separator just-return-string)
  10546. "Display the current outline path in the echo area.
  10547. If FILE is non-nil, prepend the output with the file name.
  10548. If CURRENT is non-nil, append the current heading to the output.
  10549. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10550. the different parts of the path and defaults to \"/\".
  10551. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10552. (interactive "P")
  10553. (let* (case-fold-search
  10554. (bfn (buffer-file-name (buffer-base-buffer)))
  10555. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10556. res)
  10557. (when current (setq path (append path
  10558. (save-excursion
  10559. (org-back-to-heading t)
  10560. (when (looking-at org-complex-heading-regexp)
  10561. (list (match-string 4)))))))
  10562. (setq res
  10563. (org-format-outline-path
  10564. path
  10565. (1- (frame-width))
  10566. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10567. separator))
  10568. (if just-return-string
  10569. (org-no-properties res)
  10570. (org-unlogged-message "%s" res))))
  10571. (defvar org-refile-history nil
  10572. "History for refiling operations.")
  10573. (defvar org-after-refile-insert-hook nil
  10574. "Hook run after `org-refile' has inserted its stuff at the new location.
  10575. Note that this is still *before* the stuff will be removed from
  10576. the *old* location.")
  10577. (defvar org-capture-last-stored-marker)
  10578. (defvar org-refile-keep nil
  10579. "Non-nil means `org-refile' will copy instead of refile.")
  10580. (defun org-copy ()
  10581. "Like `org-refile', but copy."
  10582. (interactive)
  10583. (let ((org-refile-keep t))
  10584. (funcall 'org-refile nil nil nil "Copy")))
  10585. (defun org-refile (&optional arg default-buffer rfloc msg)
  10586. "Move the entry or entries at point to another heading.
  10587. The list of target headings is compiled using the information in
  10588. `org-refile-targets', which see.
  10589. At the target location, the entry is filed as a subitem of the
  10590. target heading. Depending on `org-reverse-note-order', the new
  10591. subitem will either be the first or the last subitem.
  10592. If there is an active region, all entries in that region will be
  10593. refiled. However, the region must fulfill the requirement that
  10594. the first heading sets the top-level of the moved text.
  10595. With prefix arg ARG, the command will only visit the target
  10596. location and not actually move anything.
  10597. With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
  10598. refiling operation has put the subtree.
  10599. With a numeric prefix argument of `2', refile to the running clock.
  10600. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10601. being set to t and copy to the target location, don't move it.
  10602. Beware that keeping refiled entries may result in duplicated ID
  10603. properties.
  10604. RFLOC can be a refile location obtained in a different way.
  10605. MSG is a string to replace \"Refile\" in the default prompt with
  10606. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10607. See also `org-refile-use-outline-path' and `org-completion-use-ido'.
  10608. If you are using target caching (see `org-refile-use-cache'), you
  10609. have to clear the target cache in order to find new targets.
  10610. This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
  10611. prefix argument (`C-u C-u C-u C-c C-w')."
  10612. (interactive "P")
  10613. (if (member arg '(0 (64)))
  10614. (org-refile-cache-clear)
  10615. (let* ((actionmsg (cond (msg msg)
  10616. ((equal arg 3) "Refile (and keep)")
  10617. (t "Refile")))
  10618. (regionp (org-region-active-p))
  10619. (region-start (and regionp (region-beginning)))
  10620. (region-end (and regionp (region-end)))
  10621. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10622. pos it nbuf file level reversed)
  10623. (setq last-command nil)
  10624. (when regionp
  10625. (goto-char region-start)
  10626. (or (bolp) (goto-char (point-at-bol)))
  10627. (setq region-start (point))
  10628. (unless (or (org-kill-is-subtree-p
  10629. (buffer-substring region-start region-end))
  10630. (prog1 org-refile-active-region-within-subtree
  10631. (let ((s (point-at-eol)))
  10632. (org-toggle-heading)
  10633. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10634. (user-error "The region is not a (sequence of) subtree(s)")))
  10635. (if (equal arg '(16))
  10636. (org-refile-goto-last-stored)
  10637. (when (or
  10638. (and (equal arg 2)
  10639. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10640. (prog1
  10641. (setq it (list (or org-clock-heading "running clock")
  10642. (buffer-file-name
  10643. (marker-buffer org-clock-hd-marker))
  10644. ""
  10645. (marker-position org-clock-hd-marker)))
  10646. (setq arg nil)))
  10647. (setq it (or rfloc
  10648. (let (heading-text)
  10649. (save-excursion
  10650. (unless (and arg (listp arg))
  10651. (org-back-to-heading t)
  10652. (setq heading-text
  10653. (replace-regexp-in-string
  10654. org-bracket-link-regexp
  10655. "\\3"
  10656. (nth 4 (org-heading-components)))))
  10657. (org-refile-get-location
  10658. (cond ((and arg (listp arg)) "Goto")
  10659. (regionp (concat actionmsg " region to"))
  10660. (t (concat actionmsg " subtree \""
  10661. heading-text "\" to")))
  10662. default-buffer
  10663. (and (not (equal '(4) arg))
  10664. org-refile-allow-creating-parent-nodes)
  10665. arg))))))
  10666. (setq file (nth 1 it)
  10667. pos (nth 3 it))
  10668. (when (and (not arg)
  10669. pos
  10670. (equal (buffer-file-name) file)
  10671. (if regionp
  10672. (and (>= pos region-start)
  10673. (<= pos region-end))
  10674. (and (>= pos (point))
  10675. (< pos (save-excursion
  10676. (org-end-of-subtree t t))))))
  10677. (error "Cannot refile to position inside the tree or region"))
  10678. (setq nbuf (or (find-buffer-visiting file)
  10679. (find-file-noselect file)))
  10680. (if (and arg (not (equal arg 3)))
  10681. (progn
  10682. (org-pop-to-buffer-same-window nbuf)
  10683. (goto-char pos)
  10684. (org-show-context 'org-goto))
  10685. (if regionp
  10686. (progn
  10687. (org-kill-new (buffer-substring region-start region-end))
  10688. (org-save-markers-in-region region-start region-end))
  10689. (org-copy-subtree 1 nil t))
  10690. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10691. (find-file-noselect file)))
  10692. (setq reversed (org-notes-order-reversed-p))
  10693. (save-excursion
  10694. (save-restriction
  10695. (widen)
  10696. (if pos
  10697. (progn
  10698. (goto-char pos)
  10699. (looking-at org-outline-regexp)
  10700. (setq level (org-get-valid-level (funcall outline-level) 1))
  10701. (goto-char
  10702. (if reversed
  10703. (or (outline-next-heading) (point-max))
  10704. (or (save-excursion (org-get-next-sibling))
  10705. (org-end-of-subtree t t)
  10706. (point-max)))))
  10707. (setq level 1)
  10708. (if (not reversed)
  10709. (goto-char (point-max))
  10710. (goto-char (point-min))
  10711. (or (outline-next-heading) (goto-char (point-max)))))
  10712. (unless (bolp) (newline))
  10713. (org-paste-subtree level nil nil t)
  10714. (when org-log-refile
  10715. (org-add-log-setup 'refile nil nil org-log-refile)
  10716. (unless (eq org-log-refile 'note)
  10717. (save-excursion (org-add-log-note))))
  10718. (and org-auto-align-tags
  10719. (let ((org-loop-over-headlines-in-active-region nil))
  10720. (org-set-tags nil t)))
  10721. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10722. :last-refile)))
  10723. (when bookmark-name
  10724. (with-demoted-errors
  10725. (bookmark-set bookmark-name))))
  10726. ;; If we are refiling for capture, make sure that the
  10727. ;; last-capture pointers point here
  10728. (when (org-bound-and-true-p org-capture-is-refiling)
  10729. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10730. :last-capture-marker)))
  10731. (when bookmark-name
  10732. (with-demoted-errors
  10733. (bookmark-set bookmark-name))))
  10734. (move-marker org-capture-last-stored-marker (point)))
  10735. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10736. (run-hooks 'org-after-refile-insert-hook))))
  10737. (unless org-refile-keep
  10738. (if regionp
  10739. (delete-region (point) (+ (point) (- region-end region-start)))
  10740. (delete-region
  10741. (and (org-back-to-heading t) (point))
  10742. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10743. (when (featurep 'org-inlinetask)
  10744. (org-inlinetask-remove-END-maybe))
  10745. (setq org-markers-to-move nil)
  10746. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10747. (defun org-refile-goto-last-stored ()
  10748. "Go to the location where the last refile was stored."
  10749. (interactive)
  10750. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10751. (message "This is the location of the last refile"))
  10752. (defun org-refile--get-location (refloc tbl)
  10753. "When user refile to REFLOC, find the associated target in TBL.
  10754. Also check `org-refile-target-table'."
  10755. (car (delq
  10756. nil
  10757. (mapcar
  10758. (lambda (r) (or (assoc r tbl)
  10759. (assoc r org-refile-target-table)))
  10760. (list (replace-regexp-in-string "/$" "" refloc)
  10761. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10762. (defun org-refile-get-location (&optional prompt default-buffer new-nodes
  10763. no-exclude)
  10764. "Prompt the user for a refile location, using PROMPT.
  10765. PROMPT should not be suffixed with a colon and a space, because
  10766. this function appends the default value from
  10767. `org-refile-history' automatically, if that is not empty.
  10768. When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
  10769. this is used for the GOTO interface."
  10770. (let ((org-refile-targets org-refile-targets)
  10771. (org-refile-use-outline-path org-refile-use-outline-path)
  10772. excluded-entries)
  10773. (when (and (derived-mode-p 'org-mode)
  10774. (not org-refile-use-cache)
  10775. (not no-exclude))
  10776. (org-map-tree
  10777. (lambda()
  10778. (setq excluded-entries
  10779. (append excluded-entries (list (org-get-heading t t)))))))
  10780. (setq org-refile-target-table
  10781. (org-refile-get-targets default-buffer excluded-entries)))
  10782. (unless org-refile-target-table
  10783. (user-error "No refile targets"))
  10784. (let* ((cbuf (current-buffer))
  10785. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10786. (cfunc (if (and org-refile-use-outline-path
  10787. org-outline-path-complete-in-steps)
  10788. #'org-olpath-completing-read
  10789. #'completing-read))
  10790. (extra (if org-refile-use-outline-path "/" ""))
  10791. (cbnex (concat (buffer-name) extra))
  10792. (filename (and cfn (expand-file-name cfn)))
  10793. (tbl (mapcar
  10794. (lambda (x)
  10795. (if (and (not (member org-refile-use-outline-path
  10796. '(file full-file-path)))
  10797. (not (equal filename (nth 1 x))))
  10798. (cons (concat (car x) extra " ("
  10799. (file-name-nondirectory (nth 1 x)) ")")
  10800. (cdr x))
  10801. (cons (concat (car x) extra) (cdr x))))
  10802. org-refile-target-table))
  10803. (completion-ignore-case t)
  10804. cdef
  10805. (prompt (concat prompt
  10806. (or (and (car org-refile-history)
  10807. (concat " (default " (car org-refile-history) ")"))
  10808. (and (assoc cbnex tbl) (setq cdef cbnex)
  10809. (concat " (default " cbnex ")"))) ": "))
  10810. pa answ parent-target child parent old-hist)
  10811. (setq old-hist org-refile-history)
  10812. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10813. nil 'org-refile-history (or cdef (car org-refile-history))))
  10814. (if (setq pa (org-refile--get-location answ tbl))
  10815. (progn
  10816. (org-refile-check-position pa)
  10817. (when (or (not org-refile-history)
  10818. (not (eq old-hist org-refile-history))
  10819. (not (equal (car pa) (car org-refile-history))))
  10820. (setq org-refile-history
  10821. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10822. org-refile-history
  10823. (cdr org-refile-history))))
  10824. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10825. (pop org-refile-history)))
  10826. pa)
  10827. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10828. (progn
  10829. (setq parent (match-string 1 answ)
  10830. child (match-string 2 answ))
  10831. (setq parent-target (org-refile--get-location parent tbl))
  10832. (when (and parent-target
  10833. (or (eq new-nodes t)
  10834. (and (eq new-nodes 'confirm)
  10835. (y-or-n-p (format "Create new node \"%s\"? "
  10836. child)))))
  10837. (org-refile-new-child parent-target child)))
  10838. (user-error "Invalid target location")))))
  10839. (declare-function org-string-nw-p "org-macs" (s))
  10840. (defun org-refile-check-position (refile-pointer)
  10841. "Check if the refile pointer matches the headline to which it points."
  10842. (let* ((file (nth 1 refile-pointer))
  10843. (re (nth 2 refile-pointer))
  10844. (pos (nth 3 refile-pointer))
  10845. buffer)
  10846. (if (and (not (markerp pos)) (not file))
  10847. (user-error "Please indicate a target file in the refile path")
  10848. (when (org-string-nw-p re)
  10849. (setq buffer (if (markerp pos)
  10850. (marker-buffer pos)
  10851. (or (find-buffer-visiting file)
  10852. (find-file-noselect file))))
  10853. (with-current-buffer buffer
  10854. (save-excursion
  10855. (save-restriction
  10856. (widen)
  10857. (goto-char pos)
  10858. (beginning-of-line 1)
  10859. (unless (org-looking-at-p re)
  10860. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
  10861. (defun org-refile-new-child (parent-target child)
  10862. "Use refile target PARENT-TARGET to add new CHILD below it."
  10863. (unless parent-target
  10864. (error "Cannot find parent for new node"))
  10865. (let ((file (nth 1 parent-target))
  10866. (pos (nth 3 parent-target))
  10867. level)
  10868. (with-current-buffer (or (find-buffer-visiting file)
  10869. (find-file-noselect file))
  10870. (save-excursion
  10871. (save-restriction
  10872. (widen)
  10873. (if pos
  10874. (goto-char pos)
  10875. (goto-char (point-max))
  10876. (unless (bolp) (newline)))
  10877. (when (looking-at org-outline-regexp)
  10878. (setq level (funcall outline-level))
  10879. (org-end-of-subtree t t))
  10880. (org-back-over-empty-lines)
  10881. (insert "\n" (make-string
  10882. (if pos (org-get-valid-level level 1) 1) ?*)
  10883. " " child "\n")
  10884. (beginning-of-line 0)
  10885. (list (concat (car parent-target) "/" child) file "" (point)))))))
  10886. (defun org-olpath-completing-read (prompt collection &rest args)
  10887. "Read an outline path like a file name."
  10888. (let ((thetable collection))
  10889. (apply #'completing-read
  10890. prompt
  10891. (lambda (string predicate &optional flag)
  10892. (cond
  10893. ((eq flag nil) (try-completion string thetable))
  10894. ((eq flag t)
  10895. (let ((l (length string)))
  10896. (mapcar (lambda (x)
  10897. (let ((r (substring x l))
  10898. (f (if (string-match " ([^)]*)$" x)
  10899. (match-string 0 x)
  10900. "")))
  10901. (if (string-match "/" r)
  10902. (concat string (substring r 0 (match-end 0)) f)
  10903. x)))
  10904. (all-completions string thetable predicate))))
  10905. ;; Exact match?
  10906. ((eq flag 'lambda) (assoc string thetable))))
  10907. args)))
  10908. ;;;; Dynamic blocks
  10909. (defun org-find-dblock (name)
  10910. "Find the first dynamic block with name NAME in the buffer.
  10911. If not found, stay at current position and return nil."
  10912. (let ((case-fold-search t) pos)
  10913. (save-excursion
  10914. (goto-char (point-min))
  10915. (setq pos (and (re-search-forward
  10916. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10917. (match-beginning 0))))
  10918. (when pos (goto-char pos))
  10919. pos))
  10920. (defun org-create-dblock (plist)
  10921. "Create a dynamic block section, with parameters taken from PLIST.
  10922. PLIST must contain a :name entry which is used as the name of the block."
  10923. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10924. (end-of-line 1)
  10925. (newline))
  10926. (let ((col (current-column))
  10927. (name (plist-get plist :name)))
  10928. (insert "#+BEGIN: " name)
  10929. (while plist
  10930. (if (eq (car plist) :name)
  10931. (setq plist (cddr plist))
  10932. (insert " " (prin1-to-string (pop plist)))))
  10933. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10934. (beginning-of-line -2)))
  10935. (defun org-prepare-dblock ()
  10936. "Prepare dynamic block for refresh.
  10937. This empties the block, puts the cursor at the insert position and returns
  10938. the property list including an extra property :name with the block name."
  10939. (unless (looking-at org-dblock-start-re)
  10940. (user-error "Not at a dynamic block"))
  10941. (let* ((begdel (1+ (match-end 0)))
  10942. (name (org-no-properties (match-string 1)))
  10943. (params (append (list :name name)
  10944. (read (concat "(" (match-string 3) ")")))))
  10945. (save-excursion
  10946. (beginning-of-line 1)
  10947. (skip-chars-forward " \t")
  10948. (setq params (plist-put params :indentation-column (current-column))))
  10949. (unless (re-search-forward org-dblock-end-re nil t)
  10950. (error "Dynamic block not terminated"))
  10951. (setq params
  10952. (append params
  10953. (list :content (buffer-substring
  10954. begdel (match-beginning 0)))))
  10955. (delete-region begdel (match-beginning 0))
  10956. (goto-char begdel)
  10957. (open-line 1)
  10958. params))
  10959. (defun org-map-dblocks (&optional command)
  10960. "Apply COMMAND to all dynamic blocks in the current buffer.
  10961. If COMMAND is not given, use `org-update-dblock'."
  10962. (let ((cmd (or command 'org-update-dblock)))
  10963. (save-excursion
  10964. (goto-char (point-min))
  10965. (while (re-search-forward org-dblock-start-re nil t)
  10966. (goto-char (match-beginning 0))
  10967. (save-excursion
  10968. (condition-case nil
  10969. (funcall cmd)
  10970. (error (message "Error during update of dynamic block"))))
  10971. (unless (re-search-forward org-dblock-end-re nil t)
  10972. (error "Dynamic block not terminated"))))))
  10973. (defun org-dblock-update (&optional arg)
  10974. "User command for updating dynamic blocks.
  10975. Update the dynamic block at point. With prefix ARG, update all dynamic
  10976. blocks in the buffer."
  10977. (interactive "P")
  10978. (if arg
  10979. (org-update-all-dblocks)
  10980. (or (looking-at org-dblock-start-re)
  10981. (org-beginning-of-dblock))
  10982. (org-update-dblock)))
  10983. (defun org-update-dblock ()
  10984. "Update the dynamic block at point.
  10985. This means to empty the block, parse for parameters and then call
  10986. the correct writing function."
  10987. (interactive)
  10988. (save-excursion
  10989. (let* ((win (selected-window))
  10990. (pos (point))
  10991. (line (org-current-line))
  10992. (params (org-prepare-dblock))
  10993. (name (plist-get params :name))
  10994. (indent (plist-get params :indentation-column))
  10995. (cmd (intern (concat "org-dblock-write:" name))))
  10996. (message "Updating dynamic block `%s' at line %d..." name line)
  10997. (funcall cmd params)
  10998. (message "Updating dynamic block `%s' at line %d...done" name line)
  10999. (goto-char pos)
  11000. (when (and indent (> indent 0))
  11001. (setq indent (make-string indent ?\ ))
  11002. (save-excursion
  11003. (select-window win)
  11004. (org-beginning-of-dblock)
  11005. (forward-line 1)
  11006. (while (not (looking-at org-dblock-end-re))
  11007. (insert indent)
  11008. (beginning-of-line 2))
  11009. (when (looking-at org-dblock-end-re)
  11010. (and (looking-at "[ \t]+")
  11011. (replace-match ""))
  11012. (insert indent)))))))
  11013. (defun org-beginning-of-dblock ()
  11014. "Find the beginning of the dynamic block at point.
  11015. Error if there is no such block at point."
  11016. (let ((pos (point))
  11017. beg)
  11018. (end-of-line 1)
  11019. (if (and (re-search-backward org-dblock-start-re nil t)
  11020. (setq beg (match-beginning 0))
  11021. (re-search-forward org-dblock-end-re nil t)
  11022. (> (match-end 0) pos))
  11023. (goto-char beg)
  11024. (goto-char pos)
  11025. (error "Not in a dynamic block"))))
  11026. (defun org-update-all-dblocks ()
  11027. "Update all dynamic blocks in the buffer.
  11028. This function can be used in a hook."
  11029. (interactive)
  11030. (when (derived-mode-p 'org-mode)
  11031. (org-map-dblocks 'org-update-dblock)))
  11032. ;;;; Completion
  11033. (declare-function org-export-backend-name "org-export" (cl-x))
  11034. (declare-function org-export-backend-options "org-export" (cl-x))
  11035. (defun org-get-export-keywords ()
  11036. "Return a list of all currently understood export keywords.
  11037. Export keywords include options, block names, attributes and
  11038. keywords relative to each registered export back-end."
  11039. (let (keywords)
  11040. (dolist (backend
  11041. (org-bound-and-true-p org-export-registered-backends)
  11042. (delq nil keywords))
  11043. ;; Back-end name (for keywords, like #+LATEX:)
  11044. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11045. (dolist (option-entry (org-export-backend-options backend))
  11046. ;; Back-end options.
  11047. (push (nth 1 option-entry) keywords)))))
  11048. (defconst org-options-keywords
  11049. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11050. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11051. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11052. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11053. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11054. (defcustom org-structure-template-alist
  11055. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11056. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11057. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11058. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11059. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11060. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11061. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11062. ("L" "#+LaTeX: ")
  11063. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11064. ("H" "#+HTML: ")
  11065. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11066. ("A" "#+ASCII: ")
  11067. ("i" "#+INDEX: ?")
  11068. ("I" "#+INCLUDE: %file ?"))
  11069. "Structure completion elements.
  11070. This is a list of abbreviation keys and values. The value gets inserted
  11071. if you type `<' followed by the key and then press the completion key,
  11072. usually `TAB'. %file will be replaced by a file name after prompting
  11073. for the file using completion. The cursor will be placed at the position
  11074. of the `?' in the template.
  11075. There are two templates for each key, the first uses the original Org syntax,
  11076. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11077. the default when the /org-mtags.el/ module has been loaded. See also the
  11078. variable `org-mtags-prefer-muse-templates'."
  11079. :group 'org-completion
  11080. :type '(repeat
  11081. (list
  11082. (string :tag "Key")
  11083. (string :tag "Template")))
  11084. :version "25.1"
  11085. :package-version '(Org . "8.3"))
  11086. (defun org-try-structure-completion ()
  11087. "Try to complete a structure template before point.
  11088. This looks for strings like \"<e\" on an otherwise empty line and
  11089. expands them."
  11090. (let ((l (buffer-substring (point-at-bol) (point)))
  11091. a)
  11092. (when (and (looking-at "[ \t]*$")
  11093. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11094. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11095. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11096. (match-beginning 1)) a)
  11097. t)))
  11098. (defun org-complete-expand-structure-template (start cell)
  11099. "Expand a structure template."
  11100. (let ((rpl (nth 1 cell))
  11101. (ind ""))
  11102. (delete-region start (point))
  11103. (when (string-match "\\`[ \t]*#\\+" rpl)
  11104. (cond
  11105. ((bolp))
  11106. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11107. (setq ind (buffer-substring (point-at-bol) (point))))
  11108. (t (newline))))
  11109. (setq start (point))
  11110. (when (string-match "%file" rpl)
  11111. (setq rpl (replace-match
  11112. (concat
  11113. "\""
  11114. (save-match-data
  11115. (abbreviate-file-name (read-file-name "Include file: ")))
  11116. "\"")
  11117. t t rpl)))
  11118. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11119. (concat "\n" ind)))
  11120. (insert rpl)
  11121. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11122. ;;;; TODO, DEADLINE, Comments
  11123. (defun org-toggle-comment ()
  11124. "Change the COMMENT state of an entry."
  11125. (interactive)
  11126. (save-excursion
  11127. (org-back-to-heading)
  11128. (looking-at org-complex-heading-regexp)
  11129. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11130. (skip-chars-forward " \t")
  11131. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11132. (if (org-in-commented-heading-p t)
  11133. (delete-region (point)
  11134. (progn (search-forward " " (line-end-position) 'move)
  11135. (skip-chars-forward " \t")
  11136. (point)))
  11137. (insert org-comment-string)
  11138. (unless (eolp) (insert " ")))))
  11139. (defvar org-last-todo-state-is-todo nil
  11140. "This is non-nil when the last TODO state change led to a TODO state.
  11141. If the last change removed the TODO tag or switched to DONE, then
  11142. this is nil.")
  11143. (defvar org-setting-tags nil) ; dynamically skipped
  11144. (defvar org-todo-setup-filter-hook nil
  11145. "Hook for functions that pre-filter todo specs.
  11146. Each function takes a todo spec and returns either nil or the spec
  11147. transformed into canonical form." )
  11148. (defvar org-todo-get-default-hook nil
  11149. "Hook for functions that get a default item for todo.
  11150. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11151. nil or a string to be used for the todo mark." )
  11152. (defvar org-agenda-headline-snapshot-before-repeat)
  11153. (defun org-current-effective-time ()
  11154. "Return current time adjusted for `org-extend-today-until' variable."
  11155. (let* ((ct (org-current-time))
  11156. (dct (decode-time ct))
  11157. (ct1
  11158. (cond
  11159. (org-use-last-clock-out-time-as-effective-time
  11160. (or (org-clock-get-last-clock-out-time) ct))
  11161. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11162. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11163. (t ct))))
  11164. ct1))
  11165. (defun org-todo-yesterday (&optional arg)
  11166. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11167. (interactive "P")
  11168. (if (eq major-mode 'org-agenda-mode)
  11169. (apply 'org-agenda-todo-yesterday arg)
  11170. (let* ((org-use-effective-time t)
  11171. (hour (third (decode-time
  11172. (org-current-time))))
  11173. (org-extend-today-until (1+ hour)))
  11174. (org-todo arg))))
  11175. (defvar org-block-entry-blocking ""
  11176. "First entry preventing the TODO state change.")
  11177. (defun org-cancel-repeater ()
  11178. "Cancel a repeater by setting its numeric value to zero."
  11179. (interactive)
  11180. (save-excursion
  11181. (org-back-to-heading t)
  11182. (let ((bound1 (point))
  11183. (bound0 (save-excursion (outline-next-heading) (point))))
  11184. (when (and (re-search-forward
  11185. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11186. org-deadline-time-regexp "\\)\\|\\("
  11187. org-ts-regexp "\\)")
  11188. bound0 t)
  11189. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11190. bound1 t))
  11191. (replace-match "0" t nil nil 1)))))
  11192. (defun org-todo (&optional arg)
  11193. "Change the TODO state of an item.
  11194. The state of an item is given by a keyword at the start of the heading,
  11195. like
  11196. *** TODO Write paper
  11197. *** DONE Call mom
  11198. The different keywords are specified in the variable `org-todo-keywords'.
  11199. By default the available states are \"TODO\" and \"DONE\".
  11200. So for this example: when the item starts with TODO, it is changed to DONE.
  11201. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11202. DONE are present, add TODO at the beginning of the heading.
  11203. With \\[universal-argument] prefix arg, use completion to determine the new \
  11204. state.
  11205. With numeric prefix arg, switch to that state.
  11206. With a double \\[universal-argument] prefix, switch to the next set of TODO \
  11207. keywords (nextset).
  11208. With a triple \\[universal-argument] prefix, circumvent any state blocking.
  11209. With a numeric prefix arg of 0, inhibit note taking for the change.
  11210. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11211. When called through ELisp, arg is also interpreted in the following way:
  11212. `none' -> empty state
  11213. \"\"(empty string) -> switch to empty state
  11214. `done' -> switch to DONE
  11215. `nextset' -> switch to the next set of keywords
  11216. `previousset' -> switch to the previous set of keywords
  11217. \"WAITING\" -> switch to the specified keyword, but only if it
  11218. really is a member of `org-todo-keywords'."
  11219. (interactive "P")
  11220. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11221. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11222. 'region-start-level 'region))
  11223. org-loop-over-headlines-in-active-region)
  11224. (org-map-entries
  11225. `(org-todo ,arg)
  11226. org-loop-over-headlines-in-active-region
  11227. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11228. (when (equal arg '(16)) (setq arg 'nextset))
  11229. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11230. (let ((org-blocker-hook org-blocker-hook)
  11231. commentp
  11232. case-fold-search)
  11233. (when (equal arg '(64))
  11234. (setq arg nil org-blocker-hook nil))
  11235. (when (and org-blocker-hook
  11236. (or org-inhibit-blocking
  11237. (org-entry-get nil "NOBLOCKING")))
  11238. (setq org-blocker-hook nil))
  11239. (save-excursion
  11240. (catch 'exit
  11241. (org-back-to-heading t)
  11242. (when (org-in-commented-heading-p t)
  11243. (org-toggle-comment)
  11244. (setq commentp t))
  11245. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11246. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11247. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11248. (let* ((match-data (match-data))
  11249. (startpos (point-at-bol))
  11250. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11251. (org-log-done org-log-done)
  11252. (org-log-repeat org-log-repeat)
  11253. (org-todo-log-states org-todo-log-states)
  11254. (org-inhibit-logging
  11255. (if (equal arg 0)
  11256. (progn (setq arg nil) 'note) org-inhibit-logging))
  11257. (this (match-string 1))
  11258. (hl-pos (match-beginning 0))
  11259. (head (org-get-todo-sequence-head this))
  11260. (ass (assoc head org-todo-kwd-alist))
  11261. (interpret (nth 1 ass))
  11262. (done-word (nth 3 ass))
  11263. (final-done-word (nth 4 ass))
  11264. (org-last-state (or this ""))
  11265. (completion-ignore-case t)
  11266. (member (member this org-todo-keywords-1))
  11267. (tail (cdr member))
  11268. (org-state (cond
  11269. ((and org-todo-key-trigger
  11270. (or (and (equal arg '(4))
  11271. (eq org-use-fast-todo-selection 'prefix))
  11272. (and (not arg) org-use-fast-todo-selection
  11273. (not (eq org-use-fast-todo-selection
  11274. 'prefix)))))
  11275. ;; Use fast selection
  11276. (org-fast-todo-selection))
  11277. ((and (equal arg '(4))
  11278. (or (not org-use-fast-todo-selection)
  11279. (not org-todo-key-trigger)))
  11280. ;; Read a state with completion
  11281. (completing-read
  11282. "State: " (mapcar #'list org-todo-keywords-1)
  11283. nil t))
  11284. ((eq arg 'right)
  11285. (if this
  11286. (if tail (car tail) nil)
  11287. (car org-todo-keywords-1)))
  11288. ((eq arg 'left)
  11289. (unless (equal member org-todo-keywords-1)
  11290. (if this
  11291. (nth (- (length org-todo-keywords-1)
  11292. (length tail) 2)
  11293. org-todo-keywords-1)
  11294. (org-last org-todo-keywords-1))))
  11295. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11296. (setq arg nil))) ; hack to fall back to cycling
  11297. (arg
  11298. ;; user or caller requests a specific state
  11299. (cond
  11300. ((equal arg "") nil)
  11301. ((eq arg 'none) nil)
  11302. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11303. ((eq arg 'nextset)
  11304. (or (car (cdr (member head org-todo-heads)))
  11305. (car org-todo-heads)))
  11306. ((eq arg 'previousset)
  11307. (let ((org-todo-heads (reverse org-todo-heads)))
  11308. (or (car (cdr (member head org-todo-heads)))
  11309. (car org-todo-heads))))
  11310. ((car (member arg org-todo-keywords-1)))
  11311. ((stringp arg)
  11312. (user-error "State `%s' not valid in this file" arg))
  11313. ((nth (1- (prefix-numeric-value arg))
  11314. org-todo-keywords-1))))
  11315. ((null member) (or head (car org-todo-keywords-1)))
  11316. ((equal this final-done-word) nil) ;; -> make empty
  11317. ((null tail) nil) ;; -> first entry
  11318. ((memq interpret '(type priority))
  11319. (if (eq this-command last-command)
  11320. (car tail)
  11321. (if (> (length tail) 0)
  11322. (or done-word (car org-done-keywords))
  11323. nil)))
  11324. (t
  11325. (car tail))))
  11326. (org-state (or
  11327. (run-hook-with-args-until-success
  11328. 'org-todo-get-default-hook org-state org-last-state)
  11329. org-state))
  11330. (next (if org-state (concat " " org-state " ") " "))
  11331. (change-plist (list :type 'todo-state-change :from this :to org-state
  11332. :position startpos))
  11333. dolog now-done-p)
  11334. (when org-blocker-hook
  11335. (setq org-last-todo-state-is-todo
  11336. (not (member this org-done-keywords)))
  11337. (unless (save-excursion
  11338. (save-match-data
  11339. (org-with-wide-buffer
  11340. (run-hook-with-args-until-failure
  11341. 'org-blocker-hook change-plist))))
  11342. (if (org-called-interactively-p 'interactive)
  11343. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11344. this org-state org-block-entry-blocking)
  11345. ;; fail silently
  11346. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11347. this org-state org-block-entry-blocking)
  11348. (throw 'exit nil))))
  11349. (store-match-data match-data)
  11350. (replace-match next t t)
  11351. (cond ((equal this org-state)
  11352. (message "TODO state was already %s" (org-trim next)))
  11353. ((pos-visible-in-window-p hl-pos)
  11354. (message "TODO state changed to %s" (org-trim next))))
  11355. (unless head
  11356. (setq head (org-get-todo-sequence-head org-state)
  11357. ass (assoc head org-todo-kwd-alist)
  11358. interpret (nth 1 ass)
  11359. done-word (nth 3 ass)
  11360. final-done-word (nth 4 ass)))
  11361. (when (memq arg '(nextset previousset))
  11362. (message "Keyword-Set %d/%d: %s"
  11363. (- (length org-todo-sets) -1
  11364. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11365. (length org-todo-sets)
  11366. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11367. (setq org-last-todo-state-is-todo
  11368. (not (member org-state org-done-keywords)))
  11369. (setq now-done-p (and (member org-state org-done-keywords)
  11370. (not (member this org-done-keywords))))
  11371. (and logging (org-local-logging logging))
  11372. (when (and (or org-todo-log-states org-log-done)
  11373. (not (eq org-inhibit-logging t))
  11374. (not (memq arg '(nextset previousset))))
  11375. ;; we need to look at recording a time and note
  11376. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11377. (nth 2 (assoc this org-todo-log-states))))
  11378. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11379. (setq dolog 'time))
  11380. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11381. (and org-state
  11382. (member org-state org-not-done-keywords)
  11383. (not (member this org-not-done-keywords))))
  11384. ;; This is now a todo state and was not one before
  11385. ;; If there was a CLOSED time stamp, get rid of it.
  11386. (org-add-planning-info nil nil 'closed))
  11387. (when (and now-done-p org-log-done)
  11388. ;; It is now done, and it was not done before
  11389. (org-add-planning-info 'closed (org-current-effective-time))
  11390. (when (and (not dolog) (eq 'note org-log-done))
  11391. (org-add-log-setup 'done org-state this 'note)))
  11392. (when (and org-state dolog)
  11393. ;; This is a non-nil state, and we need to log it
  11394. (org-add-log-setup 'state org-state this dolog)))
  11395. ;; Fixup tag positioning
  11396. (org-todo-trigger-tag-changes org-state)
  11397. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11398. (when org-provide-todo-statistics
  11399. (org-update-parent-todo-statistics))
  11400. (run-hooks 'org-after-todo-state-change-hook)
  11401. (when (and arg (not (member org-state org-done-keywords)))
  11402. (setq head (org-get-todo-sequence-head org-state)))
  11403. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11404. ;; Do we need to trigger a repeat?
  11405. (when now-done-p
  11406. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11407. ;; This is for the agenda, take a snapshot of the headline.
  11408. (save-match-data
  11409. (setq org-agenda-headline-snapshot-before-repeat
  11410. (org-get-heading))))
  11411. (org-auto-repeat-maybe org-state))
  11412. ;; Fixup cursor location if close to the keyword
  11413. (when (and (outline-on-heading-p)
  11414. (not (bolp))
  11415. (save-excursion (beginning-of-line 1)
  11416. (looking-at org-todo-line-regexp))
  11417. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11418. (goto-char (or (match-end 2) (match-end 1)))
  11419. (and (looking-at " ") (just-one-space)))
  11420. (when org-trigger-hook
  11421. (save-excursion
  11422. (run-hook-with-args 'org-trigger-hook change-plist)))
  11423. (when commentp (org-toggle-comment))))))))
  11424. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11425. "Block turning an entry into a TODO, using the hierarchy.
  11426. This checks whether the current task should be blocked from state
  11427. changes. Such blocking occurs when:
  11428. 1. The task has children which are not all in a completed state.
  11429. 2. A task has a parent with the property :ORDERED:, and there
  11430. are siblings prior to the current task with incomplete
  11431. status.
  11432. 3. The parent of the task is blocked because it has siblings that should
  11433. be done first, or is child of a block grandparent TODO entry."
  11434. (if (not org-enforce-todo-dependencies)
  11435. t ; if locally turned off don't block
  11436. (catch 'dont-block
  11437. ;; If this is not a todo state change, or if this entry is already DONE,
  11438. ;; do not block
  11439. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11440. (member (plist-get change-plist :from)
  11441. (cons 'done org-done-keywords))
  11442. (member (plist-get change-plist :to)
  11443. (cons 'todo org-not-done-keywords))
  11444. (not (plist-get change-plist :to)))
  11445. (throw 'dont-block t))
  11446. ;; If this task has children, and any are undone, it's blocked
  11447. (save-excursion
  11448. (org-back-to-heading t)
  11449. (let ((this-level (funcall outline-level)))
  11450. (outline-next-heading)
  11451. (let ((child-level (funcall outline-level)))
  11452. (while (and (not (eobp))
  11453. (> child-level this-level))
  11454. ;; this todo has children, check whether they are all
  11455. ;; completed
  11456. (when (and (not (org-entry-is-done-p))
  11457. (org-entry-is-todo-p))
  11458. (setq org-block-entry-blocking (org-get-heading))
  11459. (throw 'dont-block nil))
  11460. (outline-next-heading)
  11461. (setq child-level (funcall outline-level))))))
  11462. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11463. ;; any previous siblings are undone, it's blocked
  11464. (save-excursion
  11465. (org-back-to-heading t)
  11466. (let* ((pos (point))
  11467. (parent-pos (and (org-up-heading-safe) (point))))
  11468. (unless parent-pos (throw 'dont-block t)) ; no parent
  11469. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11470. (forward-line 1)
  11471. (re-search-forward org-not-done-heading-regexp pos t))
  11472. (setq org-block-entry-blocking (match-string 0))
  11473. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11474. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11475. (while t
  11476. (goto-char parent-pos)
  11477. (unless (looking-at org-not-done-heading-regexp)
  11478. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11479. (setq pos (point))
  11480. (setq parent-pos (and (org-up-heading-safe) (point)))
  11481. (unless parent-pos (throw 'dont-block t)) ; no parent
  11482. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11483. (forward-line 1)
  11484. (re-search-forward org-not-done-heading-regexp pos t)
  11485. (setq org-block-entry-blocking (org-get-heading)))
  11486. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11487. (defcustom org-track-ordered-property-with-tag nil
  11488. "Should the ORDERED property also be shown as a tag?
  11489. The ORDERED property decides if an entry should require subtasks to be
  11490. completed in sequence. Since a property is not very visible, setting
  11491. this option means that toggling the ORDERED property with the command
  11492. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11493. not relevant for the behavior, but it makes things more visible.
  11494. Note that toggling the tag with tags commands will not change the property
  11495. and therefore not influence behavior!
  11496. This can be t, meaning the tag ORDERED should be used, It can also be a
  11497. string to select a different tag for this task."
  11498. :group 'org-todo
  11499. :type '(choice
  11500. (const :tag "No tracking" nil)
  11501. (const :tag "Track with ORDERED tag" t)
  11502. (string :tag "Use other tag")))
  11503. (defun org-toggle-ordered-property ()
  11504. "Toggle the ORDERED property of the current entry.
  11505. For better visibility, you can track the value of this property with a tag.
  11506. See variable `org-track-ordered-property-with-tag'."
  11507. (interactive)
  11508. (let* ((t1 org-track-ordered-property-with-tag)
  11509. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11510. (save-excursion
  11511. (org-back-to-heading)
  11512. (if (org-entry-get nil "ORDERED")
  11513. (progn
  11514. (org-delete-property "ORDERED")
  11515. (and tag (org-toggle-tag tag 'off))
  11516. (message "Subtasks can be completed in arbitrary order"))
  11517. (org-entry-put nil "ORDERED" "t")
  11518. (and tag (org-toggle-tag tag 'on))
  11519. (message "Subtasks must be completed in sequence")))))
  11520. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11521. (defun org-block-todo-from-checkboxes (change-plist)
  11522. "Block turning an entry into a TODO, using checkboxes.
  11523. This checks whether the current task should be blocked from state
  11524. changes because there are unchecked boxes in this entry."
  11525. (if (not org-enforce-todo-checkbox-dependencies)
  11526. t ; if locally turned off don't block
  11527. (catch 'dont-block
  11528. ;; If this is not a todo state change, or if this entry is already DONE,
  11529. ;; do not block
  11530. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11531. (member (plist-get change-plist :from)
  11532. (cons 'done org-done-keywords))
  11533. (member (plist-get change-plist :to)
  11534. (cons 'todo org-not-done-keywords))
  11535. (not (plist-get change-plist :to)))
  11536. (throw 'dont-block t))
  11537. ;; If this task has checkboxes that are not checked, it's blocked
  11538. (save-excursion
  11539. (org-back-to-heading t)
  11540. (let ((beg (point)) end)
  11541. (outline-next-heading)
  11542. (setq end (point))
  11543. (goto-char beg)
  11544. (when (org-list-search-forward
  11545. (concat (org-item-beginning-re)
  11546. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11547. "\\[[- ]\\]")
  11548. end t)
  11549. (when (boundp 'org-blocked-by-checkboxes)
  11550. (setq org-blocked-by-checkboxes t))
  11551. (throw 'dont-block nil))))
  11552. t))) ; do not block
  11553. (defun org-entry-blocked-p ()
  11554. "Non-nil if entry at point is blocked."
  11555. (and (not (org-entry-get nil "NOBLOCKING"))
  11556. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11557. (not (run-hook-with-args-until-failure
  11558. 'org-blocker-hook
  11559. (list :type 'todo-state-change
  11560. :position (point)
  11561. :from 'todo
  11562. :to 'done)))))
  11563. (defun org-update-statistics-cookies (all)
  11564. "Update the statistics cookie, either from TODO or from checkboxes.
  11565. This should be called with the cursor in a line with a statistics cookie."
  11566. (interactive "P")
  11567. (if all
  11568. (progn
  11569. (org-update-checkbox-count 'all)
  11570. (org-map-entries 'org-update-parent-todo-statistics))
  11571. (if (not (org-at-heading-p))
  11572. (org-update-checkbox-count)
  11573. (let ((pos (point-marker))
  11574. end l1 l2)
  11575. (ignore-errors (org-back-to-heading t))
  11576. (if (not (org-at-heading-p))
  11577. (org-update-checkbox-count)
  11578. (setq l1 (org-outline-level))
  11579. (setq end (save-excursion
  11580. (outline-next-heading)
  11581. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11582. (point)))
  11583. (if (and (save-excursion
  11584. (re-search-forward
  11585. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11586. (not (save-excursion (re-search-forward
  11587. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11588. (org-update-checkbox-count)
  11589. (if (and l2 (> l2 l1))
  11590. (progn
  11591. (goto-char end)
  11592. (org-update-parent-todo-statistics))
  11593. (goto-char pos)
  11594. (beginning-of-line 1)
  11595. (while (re-search-forward
  11596. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11597. (point-at-eol) t)
  11598. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11599. (goto-char pos)
  11600. (move-marker pos nil)))))
  11601. (defvar org-entry-property-inherited-from) ;; defined below
  11602. (defun org-update-parent-todo-statistics ()
  11603. "Update any statistics cookie in the parent of the current headline.
  11604. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11605. the entire subtree and this will travel up the hierarchy and update
  11606. statistics everywhere."
  11607. (let* ((prop (save-excursion (org-up-heading-safe)
  11608. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11609. (recursive (or (not org-hierarchical-todo-statistics)
  11610. (and prop (string-match "\\<recursive\\>" prop))))
  11611. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11612. 0))
  11613. (first t)
  11614. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11615. level ltoggle l1 new ndel
  11616. (cnt-all 0) (cnt-done 0) is-percent kwd
  11617. checkbox-beg ov ovs ove cookie-present)
  11618. (catch 'exit
  11619. (save-excursion
  11620. (beginning-of-line 1)
  11621. (setq ltoggle (funcall outline-level))
  11622. ;; Three situations are to consider:
  11623. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11624. ;; to the top-level ancestor on the headline;
  11625. ;; 2. If parent has "recursive" property, repeat up to the
  11626. ;; headline setting that property, taking inheritance into
  11627. ;; account;
  11628. ;; 3. Else, move up to direct parent and proceed only once.
  11629. (while (and (setq level (org-up-heading-safe))
  11630. (or recursive first)
  11631. (>= (point) lim))
  11632. (setq first nil cookie-present nil)
  11633. (unless (and level
  11634. (not (string-match
  11635. "\\<checkbox\\>"
  11636. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11637. "")))))
  11638. (throw 'exit nil))
  11639. (while (re-search-forward box-re (point-at-eol) t)
  11640. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11641. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11642. (save-match-data
  11643. (unless (outline-next-heading) (throw 'exit nil))
  11644. (while (and (looking-at org-complex-heading-regexp)
  11645. (> (setq l1 (length (match-string 1))) level))
  11646. (setq kwd (and (or recursive (= l1 ltoggle))
  11647. (match-string 2)))
  11648. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11649. (and (eq org-provide-todo-statistics t)
  11650. (or (member kwd org-done-keywords)))
  11651. (and (listp org-provide-todo-statistics)
  11652. (stringp (car org-provide-todo-statistics))
  11653. (or (member kwd org-provide-todo-statistics)
  11654. (member kwd org-done-keywords)))
  11655. (and (listp org-provide-todo-statistics)
  11656. (listp (car org-provide-todo-statistics))
  11657. (or (member kwd (car org-provide-todo-statistics))
  11658. (and (member kwd org-done-keywords)
  11659. (member kwd (cadr org-provide-todo-statistics))))))
  11660. (setq cnt-all (1+ cnt-all))
  11661. (and (eq org-provide-todo-statistics t)
  11662. kwd
  11663. (setq cnt-all (1+ cnt-all))))
  11664. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11665. (member kwd org-done-keywords))
  11666. (and (listp org-provide-todo-statistics)
  11667. (listp (car org-provide-todo-statistics))
  11668. (member kwd org-done-keywords)
  11669. (member kwd (cadr org-provide-todo-statistics)))
  11670. (and (listp org-provide-todo-statistics)
  11671. (stringp (car org-provide-todo-statistics))
  11672. (member kwd org-done-keywords)))
  11673. (setq cnt-done (1+ cnt-done)))
  11674. (outline-next-heading)))
  11675. (setq new
  11676. (if is-percent
  11677. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11678. (max 1 cnt-all)))
  11679. (format "[%d/%d]" cnt-done cnt-all))
  11680. ndel (- (match-end 0) checkbox-beg))
  11681. ;; handle overlays when updating cookie from column view
  11682. (when (setq ov (car (overlays-at checkbox-beg)))
  11683. (setq ovs (overlay-start ov) ove (overlay-end ov))
  11684. (delete-overlay ov))
  11685. (goto-char checkbox-beg)
  11686. (insert new)
  11687. (delete-region (point) (+ (point) ndel))
  11688. (when org-auto-align-tags (org-fix-tags-on-the-fly))
  11689. (when ov (move-overlay ov ovs ove)))
  11690. (when cookie-present
  11691. (run-hook-with-args 'org-after-todo-statistics-hook
  11692. cnt-done (- cnt-all cnt-done))))))
  11693. (run-hooks 'org-todo-statistics-hook)))
  11694. (defvar org-after-todo-statistics-hook nil
  11695. "Hook that is called after a TODO statistics cookie has been updated.
  11696. Each function is called with two arguments: the number of not-done entries
  11697. and the number of done entries.
  11698. For example, the following function, when added to this hook, will switch
  11699. an entry to DONE when all children are done, and back to TODO when new
  11700. entries are set to a TODO status. Note that this hook is only called
  11701. when there is a statistics cookie in the headline!
  11702. (defun org-summary-todo (n-done n-not-done)
  11703. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11704. (let (org-log-done org-log-states) ; turn off logging
  11705. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11706. ")
  11707. (defvar org-todo-statistics-hook nil
  11708. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11709. This hook runs even if there is no statistics cookie present, in which case
  11710. `org-after-todo-statistics-hook' would not run.")
  11711. (defun org-todo-trigger-tag-changes (state)
  11712. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11713. (let ((l org-todo-state-tags-triggers)
  11714. changes)
  11715. (when (or (not state) (equal state ""))
  11716. (setq changes (append changes (cdr (assoc "" l)))))
  11717. (when (and (stringp state) (> (length state) 0))
  11718. (setq changes (append changes (cdr (assoc state l)))))
  11719. (when (member state org-not-done-keywords)
  11720. (setq changes (append changes (cdr (assoc 'todo l)))))
  11721. (when (member state org-done-keywords)
  11722. (setq changes (append changes (cdr (assoc 'done l)))))
  11723. (dolist (c changes)
  11724. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11725. (defun org-local-logging (value)
  11726. "Get logging settings from a property VALUE."
  11727. ;; Directly set the variables, they are already local.
  11728. (setq org-log-done nil
  11729. org-log-repeat nil
  11730. org-todo-log-states nil)
  11731. (dolist (w (org-split-string value))
  11732. (let (a)
  11733. (cond
  11734. ((setq a (assoc w org-startup-options))
  11735. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11736. (set (nth 1 a) (nth 2 a))))
  11737. ((setq a (org-extract-log-state-settings w))
  11738. (and (member (car a) org-todo-keywords-1)
  11739. (push a org-todo-log-states)))))))
  11740. (defun org-get-todo-sequence-head (kwd)
  11741. "Return the head of the TODO sequence to which KWD belongs.
  11742. If KWD is not set, check if there is a text property remembering the
  11743. right sequence."
  11744. (let (p)
  11745. (cond
  11746. ((not kwd)
  11747. (or (get-text-property (point-at-bol) 'org-todo-head)
  11748. (progn
  11749. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11750. nil (point-at-eol)))
  11751. (get-text-property p 'org-todo-head))))
  11752. ((not (member kwd org-todo-keywords-1))
  11753. (car org-todo-keywords-1))
  11754. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11755. (defun org-fast-todo-selection ()
  11756. "Fast TODO keyword selection with single keys.
  11757. Returns the new TODO keyword, or nil if no state change should occur."
  11758. (let* ((fulltable org-todo-key-alist)
  11759. (done-keywords org-done-keywords) ;; needed for the faces.
  11760. (maxlen (apply 'max (mapcar
  11761. (lambda (x)
  11762. (if (stringp (car x)) (string-width (car x)) 0))
  11763. fulltable)))
  11764. (expert nil)
  11765. (fwidth (+ maxlen 3 1 3))
  11766. (ncol (/ (- (window-width) 4) fwidth))
  11767. tg cnt e c tbl
  11768. groups ingroup)
  11769. (save-excursion
  11770. (save-window-excursion
  11771. (if expert
  11772. (set-buffer (get-buffer-create " *Org todo*"))
  11773. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11774. (erase-buffer)
  11775. (setq-local org-done-keywords done-keywords)
  11776. (setq tbl fulltable cnt 0)
  11777. (while (setq e (pop tbl))
  11778. (cond
  11779. ((equal e '(:startgroup))
  11780. (push '() groups) (setq ingroup t)
  11781. (unless (= cnt 0)
  11782. (setq cnt 0)
  11783. (insert "\n"))
  11784. (insert "{ "))
  11785. ((equal e '(:endgroup))
  11786. (setq ingroup nil cnt 0)
  11787. (insert "}\n"))
  11788. ((equal e '(:newline))
  11789. (unless (= cnt 0)
  11790. (setq cnt 0)
  11791. (insert "\n")
  11792. (setq e (car tbl))
  11793. (while (equal (car tbl) '(:newline))
  11794. (insert "\n")
  11795. (setq tbl (cdr tbl)))))
  11796. (t
  11797. (setq tg (car e) c (cdr e))
  11798. (when ingroup (push tg (car groups)))
  11799. (setq tg (org-add-props tg nil 'face
  11800. (org-get-todo-face tg)))
  11801. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11802. (insert "[" c "] " tg (make-string
  11803. (- fwidth 4 (length tg)) ?\ ))
  11804. (when (= (setq cnt (1+ cnt)) ncol)
  11805. (insert "\n")
  11806. (when ingroup (insert " "))
  11807. (setq cnt 0)))))
  11808. (insert "\n")
  11809. (goto-char (point-min))
  11810. (unless expert (org-fit-window-to-buffer))
  11811. (message "[a-z..]:Set [SPC]:clear")
  11812. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11813. (cond
  11814. ((or (= c ?\C-g)
  11815. (and (= c ?q) (not (rassoc c fulltable))))
  11816. (setq quit-flag t))
  11817. ((= c ?\ ) nil)
  11818. ((setq e (rassoc c fulltable) tg (car e))
  11819. tg)
  11820. (t (setq quit-flag t)))))))
  11821. (defun org-entry-is-todo-p ()
  11822. (member (org-get-todo-state) org-not-done-keywords))
  11823. (defun org-entry-is-done-p ()
  11824. (member (org-get-todo-state) org-done-keywords))
  11825. (defun org-get-todo-state ()
  11826. "Return the TODO keyword of the current subtree."
  11827. (save-excursion
  11828. (org-back-to-heading t)
  11829. (and (looking-at org-todo-line-regexp)
  11830. (match-end 2)
  11831. (match-string 2))))
  11832. (defun org-at-date-range-p (&optional inactive-ok)
  11833. "Non-nil if point is inside a date range.
  11834. When optional argument INACTIVE-OK is non-nil, also consider
  11835. inactive time ranges.
  11836. When this function returns a non-nil value, match data is set
  11837. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11838. on INACTIVE-OK."
  11839. (interactive)
  11840. (save-excursion
  11841. (catch 'exit
  11842. (let ((pos (point)))
  11843. (skip-chars-backward "^[<\r\n")
  11844. (skip-chars-backward "<[")
  11845. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11846. (>= (match-end 0) pos)
  11847. (throw 'exit t))
  11848. (skip-chars-backward "^<[\r\n")
  11849. (skip-chars-backward "<[")
  11850. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11851. (>= (match-end 0) pos)
  11852. (throw 'exit t)))
  11853. nil)))
  11854. (defun org-get-repeat (&optional tagline)
  11855. "Check if there is a deadline/schedule with repeater in this entry."
  11856. (save-match-data
  11857. (save-excursion
  11858. (org-back-to-heading t)
  11859. (and (re-search-forward (if tagline
  11860. (concat tagline "\\s-*" org-repeat-re)
  11861. org-repeat-re)
  11862. (org-entry-end-position) t)
  11863. (match-string-no-properties 1)))))
  11864. (defvar org-last-changed-timestamp)
  11865. (defvar org-last-inserted-timestamp)
  11866. (defvar org-log-post-message)
  11867. (defvar org-log-note-purpose)
  11868. (defvar org-log-note-how nil)
  11869. (defvar org-log-note-extra)
  11870. (defun org-auto-repeat-maybe (done-word)
  11871. "Check if the current headline contains a repeated deadline/schedule.
  11872. If yes, set TODO state back to what it was and change the base date
  11873. of repeating deadline/scheduled time stamps to new date.
  11874. This function is run automatically after each state change to a DONE state."
  11875. ;; last-state is dynamically scoped into this function
  11876. (let* ((repeat (org-get-repeat))
  11877. (aa (assoc org-last-state org-todo-kwd-alist))
  11878. (interpret (nth 1 aa))
  11879. (head (nth 2 aa))
  11880. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11881. (msg "Entry repeats: ")
  11882. (org-log-done nil)
  11883. (org-todo-log-states nil)
  11884. re type n what ts time to-state)
  11885. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11886. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11887. (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
  11888. org-todo-repeat-to-state))
  11889. (unless (and to-state (member to-state org-todo-keywords-1))
  11890. (setq to-state (if (eq interpret 'type) org-last-state head)))
  11891. (org-todo to-state)
  11892. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  11893. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11894. (org-time-stamp-format t t))))
  11895. (when org-log-repeat
  11896. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11897. (memq 'org-add-log-note post-command-hook))
  11898. ;; OK, we are already setup for some record
  11899. (when (eq org-log-repeat 'note)
  11900. ;; make sure we take a note, not only a time stamp
  11901. (setq org-log-note-how 'note))
  11902. ;; Set up for taking a record
  11903. (org-add-log-setup 'state
  11904. (or done-word (car org-done-keywords))
  11905. org-last-state
  11906. org-log-repeat)))
  11907. (org-back-to-heading t)
  11908. (org-add-planning-info nil nil 'closed)
  11909. (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11910. org-deadline-time-regexp "\\)\\|\\("
  11911. org-ts-regexp "\\)"))
  11912. (while (re-search-forward
  11913. re (save-excursion (outline-next-heading) (point)) t)
  11914. (setq type (if (match-end 1) org-scheduled-string
  11915. (if (match-end 3) org-deadline-string "Plain:"))
  11916. ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
  11917. (if (not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11918. (org-remove-timestamp-with-keyword org-scheduled-string)
  11919. (setq n (string-to-number (match-string 2 ts))
  11920. what (match-string 3 ts))
  11921. (when (equal what "w") (setq n (* n 7) what "d"))
  11922. (when (and (equal what "h")
  11923. (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
  11924. (user-error
  11925. "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
  11926. ;; Preparation, see if we need to modify the start date for the change
  11927. (when (match-end 1)
  11928. (setq time (save-match-data (org-time-string-to-time ts)))
  11929. (cond
  11930. ((equal (match-string 1 ts) ".")
  11931. ;; Shift starting date to today
  11932. (org-timestamp-change
  11933. (- (org-today) (time-to-days time))
  11934. 'day))
  11935. ((equal (match-string 1 ts) "+")
  11936. (let ((nshiftmax 10) (nshift 0))
  11937. (while (or (= nshift 0)
  11938. (<= (time-to-days time)
  11939. (time-to-days (current-time))))
  11940. (when (= (incf nshift) nshiftmax)
  11941. (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
  11942. (user-error "Abort")))
  11943. (org-timestamp-change n (cdr (assoc what whata)))
  11944. (org-at-timestamp-p t)
  11945. (setq ts (match-string 1))
  11946. (setq time (save-match-data (org-time-string-to-time ts)))))
  11947. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11948. ;; rematch, so that we have everything in place for the real shift
  11949. (org-at-timestamp-p t)
  11950. (setq ts (match-string 1))
  11951. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
  11952. (save-excursion
  11953. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11954. (setq msg (concat msg type " " org-last-changed-timestamp " "))))
  11955. (setq org-log-post-message msg)
  11956. (message "%s" msg))))
  11957. (defun org-show-todo-tree (arg)
  11958. "Make a compact tree which shows all headlines marked with TODO.
  11959. The tree will show the lines where the regexp matches, and all higher
  11960. headlines above the match.
  11961. With a \\[universal-argument] prefix, prompt for a regexp to match.
  11962. With a numeric prefix N, construct a sparse tree for the Nth element
  11963. of `org-todo-keywords-1'."
  11964. (interactive "P")
  11965. (let ((case-fold-search nil)
  11966. (kwd-re
  11967. (cond ((null arg) org-not-done-regexp)
  11968. ((equal arg '(4))
  11969. (let ((kwd
  11970. (completing-read "Keyword (or KWD1|KWD2|...): "
  11971. (mapcar #'list org-todo-keywords-1))))
  11972. (concat "\\("
  11973. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11974. "\\)\\>")))
  11975. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11976. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11977. org-todo-keywords-1)))
  11978. (t (user-error "Invalid prefix argument: %s" arg)))))
  11979. (message "%d TODO entries found"
  11980. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11981. (defun org-deadline (arg &optional time)
  11982. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11983. With one universal prefix argument, remove any deadline from the item.
  11984. With two universal prefix arguments, prompt for a warning delay.
  11985. With argument TIME, set the deadline at the corresponding date. TIME
  11986. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11987. (interactive "P")
  11988. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11989. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11990. 'region-start-level 'region))
  11991. org-loop-over-headlines-in-active-region)
  11992. (org-map-entries
  11993. `(org-deadline ',arg ,time)
  11994. org-loop-over-headlines-in-active-region
  11995. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11996. (let* ((old-date (org-entry-get nil "DEADLINE"))
  11997. (old-date-time (when old-date (org-time-string-to-time old-date)))
  11998. (repeater (and old-date
  11999. (string-match
  12000. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12001. old-date)
  12002. (match-string 1 old-date))))
  12003. (cond
  12004. ((equal arg '(4))
  12005. (when (and old-date org-log-redeadline)
  12006. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12007. (org-remove-timestamp-with-keyword org-deadline-string)
  12008. (message "Item no longer has a deadline."))
  12009. ((equal arg '(16))
  12010. (save-excursion
  12011. (org-back-to-heading t)
  12012. (if (re-search-forward
  12013. org-deadline-time-regexp
  12014. (save-excursion (outline-next-heading) (point)) t)
  12015. (let* ((rpl0 (match-string 1))
  12016. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12017. (replace-match
  12018. (concat org-deadline-string
  12019. " <" rpl
  12020. (format " -%dd"
  12021. (abs
  12022. (- (time-to-days
  12023. (save-match-data
  12024. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12025. (time-to-days old-date-time))))
  12026. ">") t t))
  12027. (user-error "No deadline information to update"))))
  12028. (t
  12029. (org-add-planning-info 'deadline time 'closed)
  12030. (when (and old-date
  12031. org-log-redeadline
  12032. (not (equal old-date org-last-inserted-timestamp)))
  12033. (org-add-log-setup
  12034. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12035. (when repeater
  12036. (save-excursion
  12037. (org-back-to-heading t)
  12038. (when (re-search-forward (concat org-deadline-string " "
  12039. org-last-inserted-timestamp)
  12040. (save-excursion
  12041. (outline-next-heading) (point)) t)
  12042. (goto-char (1- (match-end 0)))
  12043. (insert " " repeater)
  12044. (setq org-last-inserted-timestamp
  12045. (concat (substring org-last-inserted-timestamp 0 -1)
  12046. " " repeater
  12047. (substring org-last-inserted-timestamp -1))))))
  12048. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12049. (defun org-schedule (arg &optional time)
  12050. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12051. With one universal prefix argument, remove any scheduling date from the item.
  12052. With two universal prefix arguments, prompt for a delay cookie.
  12053. With argument TIME, scheduled at the corresponding date. TIME can
  12054. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12055. (interactive "P")
  12056. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12057. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12058. 'region-start-level 'region))
  12059. org-loop-over-headlines-in-active-region)
  12060. (org-map-entries
  12061. `(org-schedule ',arg ,time)
  12062. org-loop-over-headlines-in-active-region
  12063. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12064. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12065. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12066. (repeater (and old-date
  12067. (string-match
  12068. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12069. old-date)
  12070. (match-string 1 old-date))))
  12071. (cond
  12072. ((equal arg '(4))
  12073. (progn
  12074. (when (and old-date org-log-reschedule)
  12075. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12076. (org-remove-timestamp-with-keyword org-scheduled-string)
  12077. (message "Item is no longer scheduled.")))
  12078. ((equal arg '(16))
  12079. (save-excursion
  12080. (org-back-to-heading t)
  12081. (if (re-search-forward
  12082. org-scheduled-time-regexp
  12083. (save-excursion (outline-next-heading) (point)) t)
  12084. (let* ((rpl0 (match-string 1))
  12085. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12086. (replace-match
  12087. (concat org-scheduled-string
  12088. " <" rpl
  12089. (format " -%dd"
  12090. (abs
  12091. (- (time-to-days
  12092. (save-match-data
  12093. (org-read-date nil t nil "Delay until" old-date-time)))
  12094. (time-to-days old-date-time))))
  12095. ">") t t))
  12096. (user-error "No scheduled information to update"))))
  12097. (t
  12098. (org-add-planning-info 'scheduled time 'closed)
  12099. (when (and old-date
  12100. org-log-reschedule
  12101. (not (equal old-date org-last-inserted-timestamp)))
  12102. (org-add-log-setup
  12103. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12104. (when repeater
  12105. (save-excursion
  12106. (org-back-to-heading t)
  12107. (when (re-search-forward (concat org-scheduled-string " "
  12108. org-last-inserted-timestamp)
  12109. (save-excursion
  12110. (outline-next-heading) (point)) t)
  12111. (goto-char (1- (match-end 0)))
  12112. (insert " " repeater)
  12113. (setq org-last-inserted-timestamp
  12114. (concat (substring org-last-inserted-timestamp 0 -1)
  12115. " " repeater
  12116. (substring org-last-inserted-timestamp -1))))))
  12117. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12118. (defun org-get-scheduled-time (pom &optional inherit)
  12119. "Get the scheduled time as a time tuple, of a format suitable
  12120. for calling org-schedule with, or if there is no scheduling,
  12121. returns nil."
  12122. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12123. (when time
  12124. (apply 'encode-time (org-parse-time-string time)))))
  12125. (defun org-get-deadline-time (pom &optional inherit)
  12126. "Get the deadline as a time tuple, of a format suitable for
  12127. calling org-deadline with, or if there is no scheduling, returns
  12128. nil."
  12129. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12130. (when time
  12131. (apply 'encode-time (org-parse-time-string time)))))
  12132. (defun org-remove-timestamp-with-keyword (keyword)
  12133. "Remove all time stamps with KEYWORD in the current entry."
  12134. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12135. beg)
  12136. (save-excursion
  12137. (org-back-to-heading t)
  12138. (setq beg (point))
  12139. (outline-next-heading)
  12140. (while (re-search-backward re beg t)
  12141. (replace-match "")
  12142. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12143. (equal (char-before) ?\ ))
  12144. (backward-delete-char 1)
  12145. (when (string-match "^[ \t]*$" (buffer-substring
  12146. (point-at-bol) (point-at-eol)))
  12147. (delete-region (point-at-bol)
  12148. (min (point-max) (1+ (point-at-eol))))))))))
  12149. (defvar org-time-was-given) ; dynamically scoped parameter
  12150. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12151. (defun org-at-planning-p ()
  12152. "Non-nil when point is on a planning info line."
  12153. ;; This is as accurate and faster than `org-element-at-point' since
  12154. ;; planning info location is fixed in the section.
  12155. (org-with-wide-buffer
  12156. (beginning-of-line)
  12157. (and (org-looking-at-p org-planning-line-re)
  12158. (eq (point)
  12159. (ignore-errors
  12160. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12161. (org-back-to-heading t)
  12162. (org-with-limited-levels (org-back-to-heading t)))
  12163. (line-beginning-position 2))))))
  12164. (defun org-add-planning-info (what &optional time &rest remove)
  12165. "Insert new timestamp with keyword in the planning line.
  12166. WHAT indicates what kind of time stamp to add. It is a symbol
  12167. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12168. the time to use. If none is given, the user is prompted for
  12169. a date. REMOVE indicates what kind of entries to remove. An old
  12170. WHAT entry will also be removed."
  12171. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12172. (catch 'exit
  12173. (when (and (memq what '(scheduled deadline))
  12174. (or (not time)
  12175. (and (stringp time)
  12176. (string-match "^[-+]+[0-9]" time))))
  12177. ;; Try to get a default date/time from existing timestamp
  12178. (save-excursion
  12179. (org-back-to-heading t)
  12180. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12181. (when (re-search-forward (if (eq what 'scheduled)
  12182. org-scheduled-time-regexp
  12183. org-deadline-time-regexp)
  12184. end t)
  12185. (setq ts (match-string 1)
  12186. default-time (apply 'encode-time (org-parse-time-string ts))
  12187. default-input (and ts (org-get-compact-tod ts)))))))
  12188. (when what
  12189. (setq time
  12190. (if (stringp time)
  12191. ;; This is a string (relative or absolute), set
  12192. ;; proper date.
  12193. (apply #'encode-time
  12194. (org-read-date-analyze
  12195. time default-time (decode-time default-time)))
  12196. ;; If necessary, get the time from the user
  12197. (or time (org-read-date nil 'to-time nil nil
  12198. default-time default-input)))))
  12199. (org-with-wide-buffer
  12200. (org-back-to-heading t)
  12201. (forward-line)
  12202. (unless (bolp) (insert "\n"))
  12203. (cond ((org-looking-at-p org-planning-line-re)
  12204. ;; Move to current indentation.
  12205. (skip-chars-forward " \t")
  12206. ;; Check if we have to remove something.
  12207. (dolist (type (if what (cons what remove) remove))
  12208. (save-excursion
  12209. (when (re-search-forward
  12210. (case type
  12211. (closed org-closed-time-regexp)
  12212. (deadline org-deadline-time-regexp)
  12213. (scheduled org-scheduled-time-regexp)
  12214. (otherwise
  12215. (error "Invalid planning type: %s" type)))
  12216. (line-end-position) t)
  12217. ;; Delete until next keyword or end of line.
  12218. (delete-region
  12219. (match-beginning 0)
  12220. (if (re-search-forward org-keyword-time-not-clock-regexp
  12221. (line-end-position)
  12222. t)
  12223. (match-beginning 0)
  12224. (line-end-position))))))
  12225. ;; If there is nothing more to add and no more keyword
  12226. ;; is left, remove the line completely.
  12227. (if (and (org-looking-at-p "[ \t]*$") (not what))
  12228. (delete-region (line-beginning-position)
  12229. (line-beginning-position 2))
  12230. ;; If we removed last keyword, do not leave trailing
  12231. ;; white space at the end of line.
  12232. (let ((p (point)))
  12233. (save-excursion
  12234. (end-of-line)
  12235. (unless (= (skip-chars-backward " \t" p) 0)
  12236. (delete-region (point) (line-end-position)))))))
  12237. ((not what) (throw 'exit nil)) ; Nothing to do.
  12238. (t (insert-before-markers "\n")
  12239. (backward-char 1)
  12240. (when org-adapt-indentation
  12241. (org-indent-to-column (1+ (org-outline-level))))))
  12242. (when what
  12243. ;; Insert planning keyword.
  12244. (insert (case what
  12245. (closed org-closed-string)
  12246. (deadline org-deadline-string)
  12247. (scheduled org-scheduled-string)
  12248. (otherwise (error "Invalid planning type: %s" what)))
  12249. " ")
  12250. ;; Insert associated timestamp.
  12251. (let ((ts (org-insert-time-stamp
  12252. time
  12253. (or org-time-was-given
  12254. (and (eq what 'closed) org-log-done-with-time))
  12255. (eq what 'closed)
  12256. nil nil (list org-end-time-was-given))))
  12257. (unless (eolp) (insert " "))
  12258. ts))))))
  12259. (defvar org-log-note-marker (make-marker)
  12260. "Marker pointing at the entry where the note is to be inserted.")
  12261. (defvar org-log-note-purpose nil)
  12262. (defvar org-log-note-state nil)
  12263. (defvar org-log-note-previous-state nil)
  12264. (defvar org-log-note-extra nil)
  12265. (defvar org-log-note-window-configuration nil)
  12266. (defvar org-log-note-return-to (make-marker))
  12267. (defvar org-log-note-effective-time nil
  12268. "Remembered current time so that dynamically scoped
  12269. `org-extend-today-until' affects timestamps in state change log")
  12270. (defvar org-log-post-message nil
  12271. "Message to be displayed after a log note has been stored.
  12272. The auto-repeater uses this.")
  12273. (defun org-add-note ()
  12274. "Add a note to the current entry.
  12275. This is done in the same way as adding a state change note."
  12276. (interactive)
  12277. (org-add-log-setup 'note))
  12278. (defun org-log-beginning (&optional create)
  12279. "Return expected start of log notes in current entry.
  12280. When optional argument CREATE is non-nil, the function creates
  12281. a drawer to store notes, if necessary. Returned position ignores
  12282. narrowing."
  12283. (org-with-wide-buffer
  12284. (let ((drawer (org-log-into-drawer)))
  12285. (cond
  12286. (drawer
  12287. (org-end-of-meta-data)
  12288. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12289. (end (if (org-at-heading-p) (point)
  12290. (save-excursion (outline-next-heading) (point))))
  12291. (case-fold-search t))
  12292. (catch 'exit
  12293. ;; Try to find existing drawer.
  12294. (while (re-search-forward regexp end t)
  12295. (let ((element (org-element-at-point)))
  12296. (when (eq (org-element-type element) 'drawer)
  12297. (let ((cend (org-element-property :contents-end element)))
  12298. (when (and (not org-log-states-order-reversed) cend)
  12299. (goto-char cend)))
  12300. (throw 'exit nil))))
  12301. ;; No drawer found. Create one, if permitted.
  12302. (when create
  12303. (unless (bolp) (insert "\n"))
  12304. (let ((beg (point)))
  12305. (insert ":" drawer ":\n:END:\n")
  12306. (org-indent-region beg (point)))
  12307. (end-of-line -1)))))
  12308. (t
  12309. (when org-log-state-notes-insert-after-drawers (org-end-of-meta-data t))
  12310. (skip-chars-forward " \t\n")
  12311. (beginning-of-line)
  12312. (unless org-log-states-order-reversed
  12313. (org-skip-over-state-notes)
  12314. (skip-chars-backward " \t\n")
  12315. (forward-line)))))
  12316. (if (bolp) (point) (line-beginning-position 2))))
  12317. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12318. "Set up the post command hook to take a note.
  12319. If this is about to TODO state change, the new state is expected in STATE.
  12320. HOW is an indicator what kind of note should be created.
  12321. EXTRA is additional text that will be inserted into the notes buffer."
  12322. (move-marker org-log-note-marker (point))
  12323. (setq org-log-note-purpose purpose
  12324. org-log-note-state state
  12325. org-log-note-previous-state prev-state
  12326. org-log-note-how how
  12327. org-log-note-extra extra
  12328. org-log-note-effective-time (org-current-effective-time))
  12329. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12330. (defun org-skip-over-state-notes ()
  12331. "Skip past the list of State notes in an entry."
  12332. (when (ignore-errors (goto-char (org-in-item-p)))
  12333. (let* ((struct (org-list-struct))
  12334. (prevs (org-list-prevs-alist struct))
  12335. (regexp
  12336. (concat "[ \t]*- +"
  12337. (replace-regexp-in-string
  12338. " +" " +"
  12339. (org-replace-escapes
  12340. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12341. `(("%d" . ,org-ts-regexp-inactive)
  12342. ("%D" . ,org-ts-regexp)
  12343. ("%s" . "\"\\S-+\"")
  12344. ("%S" . "\"\\S-+\"")
  12345. ("%t" . ,org-ts-regexp-inactive)
  12346. ("%T" . ,org-ts-regexp)
  12347. ("%u" . ".*?")
  12348. ("%U" . ".*?")))))))
  12349. (while (org-looking-at-p regexp)
  12350. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12351. (org-list-get-item-end (point) struct)))))))
  12352. (defun org-add-log-note (&optional _purpose)
  12353. "Pop up a window for taking a note, and add this note later."
  12354. (remove-hook 'post-command-hook 'org-add-log-note)
  12355. (setq org-log-note-window-configuration (current-window-configuration))
  12356. (delete-other-windows)
  12357. (move-marker org-log-note-return-to (point))
  12358. (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12359. (goto-char org-log-note-marker)
  12360. (org-switch-to-buffer-other-window "*Org Note*")
  12361. (erase-buffer)
  12362. (if (memq org-log-note-how '(time state))
  12363. (let (current-prefix-arg) (org-store-log-note))
  12364. (let ((org-inhibit-startup t)) (org-mode))
  12365. (insert (format "# Insert note for %s.
  12366. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12367. (cond
  12368. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12369. ((eq org-log-note-purpose 'done) "closed todo item")
  12370. ((eq org-log-note-purpose 'state)
  12371. (format "state change from \"%s\" to \"%s\""
  12372. (or org-log-note-previous-state "")
  12373. (or org-log-note-state "")))
  12374. ((eq org-log-note-purpose 'reschedule)
  12375. "rescheduling")
  12376. ((eq org-log-note-purpose 'delschedule)
  12377. "no longer scheduled")
  12378. ((eq org-log-note-purpose 'redeadline)
  12379. "changing deadline")
  12380. ((eq org-log-note-purpose 'deldeadline)
  12381. "removing deadline")
  12382. ((eq org-log-note-purpose 'refile)
  12383. "refiling")
  12384. ((eq org-log-note-purpose 'note)
  12385. "this entry")
  12386. (t (error "This should not happen")))))
  12387. (when org-log-note-extra (insert org-log-note-extra))
  12388. (setq-local org-finish-function 'org-store-log-note)
  12389. (run-hooks 'org-log-buffer-setup-hook)))
  12390. (defvar org-note-abort nil) ; dynamically scoped
  12391. (defun org-store-log-note ()
  12392. "Finish taking a log note, and insert it to where it belongs."
  12393. (let ((txt (prog1 (buffer-string)
  12394. (kill-buffer)))
  12395. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12396. lines)
  12397. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12398. (setq txt (replace-match "" t t txt)))
  12399. (when (string-match "\\s-+\\'" txt)
  12400. (setq txt (replace-match "" t t txt)))
  12401. (setq lines (org-split-string txt "\n"))
  12402. (when (org-string-nw-p note)
  12403. (setq note
  12404. (org-replace-escapes
  12405. note
  12406. (list (cons "%u" (user-login-name))
  12407. (cons "%U" user-full-name)
  12408. (cons "%t" (format-time-string
  12409. (org-time-stamp-format 'long 'inactive)
  12410. org-log-note-effective-time))
  12411. (cons "%T" (format-time-string
  12412. (org-time-stamp-format 'long nil)
  12413. org-log-note-effective-time))
  12414. (cons "%d" (format-time-string
  12415. (org-time-stamp-format nil 'inactive)
  12416. org-log-note-effective-time))
  12417. (cons "%D" (format-time-string
  12418. (org-time-stamp-format nil nil)
  12419. org-log-note-effective-time))
  12420. (cons "%s" (cond
  12421. ((not org-log-note-state) "")
  12422. ((org-string-match-p org-ts-regexp
  12423. org-log-note-state)
  12424. (format "\"[%s]\""
  12425. (substring org-log-note-state 1 -1)))
  12426. (t (format "\"%s\"" org-log-note-state))))
  12427. (cons "%S"
  12428. (cond
  12429. ((not org-log-note-previous-state) "")
  12430. ((org-string-match-p org-ts-regexp
  12431. org-log-note-previous-state)
  12432. (format "\"[%s]\""
  12433. (substring
  12434. org-log-note-previous-state 1 -1)))
  12435. (t (format "\"%s\""
  12436. org-log-note-previous-state)))))))
  12437. (when lines (setq note (concat note " \\\\")))
  12438. (push note lines))
  12439. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12440. (with-current-buffer (marker-buffer org-log-note-marker)
  12441. (org-with-wide-buffer
  12442. ;; Find location for the new note.
  12443. (goto-char org-log-note-marker)
  12444. (set-marker org-log-note-marker nil)
  12445. (goto-char (org-log-beginning t))
  12446. ;; Make sure point is at the beginning of an empty line.
  12447. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12448. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12449. ;; In an existing list, add a new item at the top level.
  12450. ;; Otherwise, indent line like a regular one.
  12451. (let ((itemp (org-in-item-p)))
  12452. (if itemp
  12453. (org-indent-line-to
  12454. (let ((struct (save-excursion
  12455. (goto-char itemp) (org-list-struct))))
  12456. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12457. (org-indent-line)))
  12458. (insert (org-list-bullet-string "-") (pop lines))
  12459. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12460. (dolist (line lines)
  12461. (insert "\n")
  12462. (org-indent-line-to ind)
  12463. (insert line)))
  12464. (message "Note stored")
  12465. (org-back-to-heading t)
  12466. (org-cycle-hide-drawers 'children))
  12467. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12468. ;; from within `org-add-log-note' because `buffer-undo-list'
  12469. ;; is then modified outside of `org-with-remote-undo'.
  12470. (when (eq this-command 'org-agenda-todo)
  12471. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12472. ;; Don't add undo information when called from `org-agenda-todo'.
  12473. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12474. (set-window-configuration org-log-note-window-configuration)
  12475. (with-current-buffer (marker-buffer org-log-note-return-to)
  12476. (goto-char org-log-note-return-to))
  12477. (move-marker org-log-note-return-to nil)
  12478. (when org-log-post-message (message "%s" org-log-post-message))))
  12479. (defun org-remove-empty-drawer-at (pos)
  12480. "Remove an empty drawer at position POS.
  12481. POS may also be a marker."
  12482. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12483. (org-with-wide-buffer
  12484. (goto-char pos)
  12485. (let ((drawer (org-element-at-point)))
  12486. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12487. (not (org-element-property :contents-begin drawer)))
  12488. (delete-region (org-element-property :begin drawer)
  12489. (progn (goto-char (org-element-property :end drawer))
  12490. (skip-chars-backward " \r\t\n")
  12491. (forward-line)
  12492. (point))))))))
  12493. (defvar org-ts-type nil)
  12494. (defun org-sparse-tree (&optional arg type)
  12495. "Create a sparse tree, prompt for the details.
  12496. This command can create sparse trees. You first need to select the type
  12497. of match used to create the tree:
  12498. t Show all TODO entries.
  12499. T Show entries with a specific TODO keyword.
  12500. m Show entries selected by a tags/property match.
  12501. p Enter a property name and its value (both with completion on existing
  12502. names/values) and show entries with that property.
  12503. r Show entries matching a regular expression (`/' can be used as well).
  12504. b Show deadlines and scheduled items before a date.
  12505. a Show deadlines and scheduled items after a date.
  12506. d Show deadlines due within `org-deadline-warning-days'.
  12507. D Show deadlines and scheduled items between a date range."
  12508. (interactive "P")
  12509. (setq type (or type org-sparse-tree-default-date-type))
  12510. (setq org-ts-type type)
  12511. (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12512. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  12513. [c]ycle through date types: %s"
  12514. (case type
  12515. (all "all timestamps")
  12516. (scheduled "only scheduled")
  12517. (deadline "only deadline")
  12518. (active "only active timestamps")
  12519. (inactive "only inactive timestamps")
  12520. (closed "with a closed time-stamp")
  12521. (otherwise "scheduled/deadline")))
  12522. (let ((answer (read-char-exclusive)))
  12523. (case answer
  12524. (?c
  12525. (org-sparse-tree
  12526. arg
  12527. (cadr
  12528. (memq type '(nil all scheduled deadline active inactive closed)))))
  12529. (?d (call-interactively 'org-check-deadlines))
  12530. (?b (call-interactively 'org-check-before-date))
  12531. (?a (call-interactively 'org-check-after-date))
  12532. (?D (call-interactively 'org-check-dates-range))
  12533. (?t (call-interactively 'org-show-todo-tree))
  12534. (?T (org-show-todo-tree '(4)))
  12535. (?m (call-interactively 'org-match-sparse-tree))
  12536. ((?p ?P)
  12537. (let* ((kwd (completing-read
  12538. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12539. (value (completing-read
  12540. "Value: " (mapcar #'list (org-property-values kwd)))))
  12541. (unless (string-match "\\`{.*}\\'" value)
  12542. (setq value (concat "\"" value "\"")))
  12543. (org-match-sparse-tree arg (concat kwd "=" value))))
  12544. ((?r ?R ?/) (call-interactively 'org-occur))
  12545. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12546. (defvar-local org-occur-highlights nil
  12547. "List of overlays used for occur matches.")
  12548. (defvar-local org-occur-parameters nil
  12549. "Parameters of the active org-occur calls.
  12550. This is a list, each call to org-occur pushes as cons cell,
  12551. containing the regular expression and the callback, onto the list.
  12552. The list can contain several entries if `org-occur' has been called
  12553. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12554. will only contain one set of parameters. When the highlights are
  12555. removed (for example with `C-c C-c', or with the next edit (depending
  12556. on `org-remove-highlights-with-change'), this variable is emptied
  12557. as well.")
  12558. (defun org-occur (regexp &optional keep-previous callback)
  12559. "Make a compact tree which shows all matches of REGEXP.
  12560. The tree will show the lines where the regexp matches, and all higher
  12561. headlines above the match. It will also show the heading after the match,
  12562. to make sure editing the matching entry is easy.
  12563. If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
  12564. call to `org-occur' will be kept, to allow stacking of calls to this
  12565. command.
  12566. If CALLBACK is non-nil, it is a function which is called to confirm
  12567. that the match should indeed be shown."
  12568. (interactive "sRegexp: \nP")
  12569. (when (equal regexp "")
  12570. (user-error "Regexp cannot be empty"))
  12571. (unless keep-previous
  12572. (org-remove-occur-highlights nil nil t))
  12573. (push (cons regexp callback) org-occur-parameters)
  12574. (let ((cnt 0))
  12575. (save-excursion
  12576. (goto-char (point-min))
  12577. (when (or (not keep-previous) ; do not want to keep
  12578. (not org-occur-highlights)) ; no previous matches
  12579. ;; hide everything
  12580. (org-overview))
  12581. (while (re-search-forward regexp nil t)
  12582. (backward-char) ;; FIXME: Match timestamps at the end of a headline
  12583. (when (or (not callback)
  12584. (save-match-data (funcall callback)))
  12585. (setq cnt (1+ cnt))
  12586. (when org-highlight-sparse-tree-matches
  12587. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12588. (org-show-context 'occur-tree))))
  12589. (when org-remove-highlights-with-change
  12590. (org-add-hook 'before-change-functions 'org-remove-occur-highlights
  12591. nil 'local))
  12592. (unless org-sparse-tree-open-archived-trees
  12593. (org-hide-archived-subtrees (point-min) (point-max)))
  12594. (run-hooks 'org-occur-hook)
  12595. (when (org-called-interactively-p 'interactive)
  12596. (message "%d match(es) for regexp %s" cnt regexp))
  12597. cnt))
  12598. (defun org-occur-next-match (&optional n _reset)
  12599. "Function for `next-error-function' to find sparse tree matches.
  12600. N is the number of matches to move, when negative move backwards.
  12601. This function always goes back to the starting point when no
  12602. match is found."
  12603. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12604. (search-func (if (< n 0)
  12605. 'previous-single-char-property-change
  12606. 'next-single-char-property-change))
  12607. (n (abs n))
  12608. (pos (point))
  12609. p1)
  12610. (catch 'exit
  12611. (while (setq p1 (funcall search-func (point) 'org-type))
  12612. (when (equal p1 limit)
  12613. (goto-char pos)
  12614. (user-error "No more matches"))
  12615. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12616. (setq n (1- n))
  12617. (when (= n 0)
  12618. (goto-char p1)
  12619. (throw 'exit (point))))
  12620. (goto-char p1))
  12621. (goto-char p1)
  12622. (user-error "No more matches"))))
  12623. (defun org-show-context (&optional key)
  12624. "Make sure point and context are visible.
  12625. Optional argument KEY, when non-nil, is a symbol. See
  12626. `org-show-context-detail' for allowed values and how much is to
  12627. be shown."
  12628. (org-show-set-visibility
  12629. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12630. ((cdr (assq key org-show-context-detail)))
  12631. (t (cdr (assq 'default org-show-context-detail))))))
  12632. (defun org-show-set-visibility (detail)
  12633. "Set visibility around point according to DETAIL.
  12634. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12635. `tree', `canonical' or t. See `org-show-context-detail' for more
  12636. information."
  12637. (unless (org-before-first-heading-p)
  12638. ;; Show current heading and possibly its entry, following headline
  12639. ;; or all children.
  12640. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12641. (org-flag-heading nil)
  12642. (org-show-entry)
  12643. (org-with-limited-levels
  12644. (case detail
  12645. ((tree canonical t) (org-show-children))
  12646. ((nil minimal ancestors))
  12647. (t (save-excursion
  12648. (outline-next-heading)
  12649. (org-flag-heading nil))))))
  12650. ;; Show all siblings.
  12651. (when (eq detail 'lineage) (org-show-siblings))
  12652. ;; Show ancestors, possibly with their children.
  12653. (when (memq detail '(ancestors lineage tree canonical t))
  12654. (save-excursion
  12655. (while (org-up-heading-safe)
  12656. (org-flag-heading nil)
  12657. (when (memq detail '(canonical t)) (org-show-entry))
  12658. (when (memq detail '(tree canonical t)) (org-show-children)))))))
  12659. (defvar org-reveal-start-hook nil
  12660. "Hook run before revealing a location.")
  12661. (defun org-reveal (&optional siblings)
  12662. "Show current entry, hierarchy above it, and the following headline.
  12663. This can be used to show a consistent set of context around
  12664. locations exposed with `org-show-context'.
  12665. With optional argument SIBLINGS, on each level of the hierarchy all
  12666. siblings are shown. This repairs the tree structure to what it would
  12667. look like when opened with hierarchical calls to `org-cycle'.
  12668. With double optional argument \\[universal-argument] \\[universal-argument], \
  12669. go to the parent and show the
  12670. entire tree."
  12671. (interactive "P")
  12672. (run-hooks 'org-reveal-start-hook)
  12673. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12674. ((equal siblings '(16))
  12675. (save-excursion
  12676. (when (org-up-heading-safe)
  12677. (org-show-subtree)
  12678. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12679. (t (org-show-set-visibility 'lineage))))
  12680. (defun org-highlight-new-match (beg end)
  12681. "Highlight from BEG to END and mark the highlight is an occur headline."
  12682. (let ((ov (make-overlay beg end)))
  12683. (overlay-put ov 'face 'secondary-selection)
  12684. (overlay-put ov 'org-type 'org-occur)
  12685. (push ov org-occur-highlights)))
  12686. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12687. "Remove the occur highlights from the buffer.
  12688. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12689. from the `before-change-functions' in the current buffer."
  12690. (interactive)
  12691. (unless org-inhibit-highlight-removal
  12692. (mapc 'delete-overlay org-occur-highlights)
  12693. (setq org-occur-highlights nil)
  12694. (setq org-occur-parameters nil)
  12695. (unless noremove
  12696. (remove-hook 'before-change-functions
  12697. 'org-remove-occur-highlights 'local))))
  12698. ;;;; Priorities
  12699. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12700. "Regular expression matching the priority indicator.")
  12701. (defvar org-remove-priority-next-time nil)
  12702. (defun org-priority-up ()
  12703. "Increase the priority of the current item."
  12704. (interactive)
  12705. (org-priority 'up))
  12706. (defun org-priority-down ()
  12707. "Decrease the priority of the current item."
  12708. (interactive)
  12709. (org-priority 'down))
  12710. (defun org-priority (&optional action _show)
  12711. "Change the priority of an item.
  12712. ACTION can be `set', `up', `down', or a character."
  12713. (interactive "P")
  12714. (if (equal action '(4))
  12715. (org-show-priority)
  12716. (unless org-enable-priority-commands
  12717. (user-error "Priority commands are disabled"))
  12718. (setq action (or action 'set))
  12719. (let (current new news have remove)
  12720. (save-excursion
  12721. (org-back-to-heading t)
  12722. (when (looking-at org-priority-regexp)
  12723. (setq current (string-to-char (match-string 2))
  12724. have t))
  12725. (cond
  12726. ((eq action 'remove)
  12727. (setq remove t new ?\ ))
  12728. ((or (eq action 'set)
  12729. (if (featurep 'xemacs) (characterp action) (integerp action)))
  12730. (if (not (eq action 'set))
  12731. (setq new action)
  12732. (message "Priority %c-%c, SPC to remove: "
  12733. org-highest-priority org-lowest-priority)
  12734. (save-match-data
  12735. (setq new (read-char-exclusive))))
  12736. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12737. (= (upcase org-lowest-priority) org-lowest-priority))
  12738. (setq new (upcase new)))
  12739. (cond ((equal new ?\ ) (setq remove t))
  12740. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12741. (user-error "Priority must be between `%c' and `%c'"
  12742. org-highest-priority org-lowest-priority))))
  12743. ((eq action 'up)
  12744. (setq new (if have
  12745. (1- current) ; normal cycling
  12746. ;; last priority was empty
  12747. (if (eq last-command this-command)
  12748. org-lowest-priority ; wrap around empty to lowest
  12749. ;; default
  12750. (if org-priority-start-cycle-with-default
  12751. org-default-priority
  12752. (1- org-default-priority))))))
  12753. ((eq action 'down)
  12754. (setq new (if have
  12755. (1+ current) ; normal cycling
  12756. ;; last priority was empty
  12757. (if (eq last-command this-command)
  12758. org-highest-priority ; wrap around empty to highest
  12759. ;; default
  12760. (if org-priority-start-cycle-with-default
  12761. org-default-priority
  12762. (1+ org-default-priority))))))
  12763. (t (user-error "Invalid action")))
  12764. (when (or (< (upcase new) org-highest-priority)
  12765. (> (upcase new) org-lowest-priority))
  12766. (if (and (memq action '(up down))
  12767. (not have) (not (eq last-command this-command)))
  12768. ;; `new' is from default priority
  12769. (error
  12770. "The default can not be set, see `org-default-priority' why")
  12771. ;; normal cycling: `new' is beyond highest/lowest priority
  12772. ;; and is wrapped around to the empty priority
  12773. (setq remove t)))
  12774. (setq news (format "%c" new))
  12775. (if have
  12776. (if remove
  12777. (replace-match "" t t nil 1)
  12778. (replace-match news t t nil 2))
  12779. (if remove
  12780. (user-error "No priority cookie found in line")
  12781. (let ((case-fold-search nil))
  12782. (looking-at org-todo-line-regexp))
  12783. (if (match-end 2)
  12784. (progn
  12785. (goto-char (match-end 2))
  12786. (insert " [#" news "]"))
  12787. (goto-char (match-beginning 3))
  12788. (insert "[#" news "] "))))
  12789. (org-set-tags nil 'align))
  12790. (if remove
  12791. (message "Priority removed")
  12792. (message "Priority of current item set to %s" news)))))
  12793. (defun org-show-priority ()
  12794. "Show the priority of the current item.
  12795. This priority is composed of the main priority given with the [#A] cookies,
  12796. and by additional input from the age of a schedules or deadline entry."
  12797. (interactive)
  12798. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12799. (org-get-at-bol 'priority)
  12800. (save-excursion
  12801. (save-match-data
  12802. (beginning-of-line)
  12803. (and (looking-at org-heading-regexp)
  12804. (org-get-priority (match-string 0))))))))
  12805. (message "Priority is %d" (if pri pri -1000))))
  12806. (defun org-get-priority (s)
  12807. "Find priority cookie and return priority."
  12808. (save-match-data
  12809. (if (functionp org-get-priority-function)
  12810. (funcall org-get-priority-function)
  12811. (if (not (string-match org-priority-regexp s))
  12812. (* 1000 (- org-lowest-priority org-default-priority))
  12813. (* 1000 (- org-lowest-priority
  12814. (string-to-char (match-string 2 s))))))))
  12815. ;;;; Tags
  12816. (defvar org-agenda-archives-mode)
  12817. (defvar org-map-continue-from nil
  12818. "Position from where mapping should continue.
  12819. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12820. (defvar org-scanner-tags nil
  12821. "The current tag list while the tags scanner is running.")
  12822. (defvar org-trust-scanner-tags nil
  12823. "Should `org-get-tags-at' use the tags for the scanner.
  12824. This is for internal dynamical scoping only.
  12825. When this is non-nil, the function `org-get-tags-at' will return the value
  12826. of `org-scanner-tags' instead of building the list by itself. This
  12827. can lead to large speed-ups when the tags scanner is used in a file with
  12828. many entries, and when the list of tags is retrieved, for example to
  12829. obtain a list of properties. Building the tags list for each entry in such
  12830. a file becomes an N^2 operation - but with this variable set, it scales
  12831. as N.")
  12832. (defvar org--matcher-tags-todo-only nil)
  12833. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12834. "Scan headline tags with inheritance and produce output ACTION.
  12835. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12836. or `agenda' to produce an entry list for an agenda view. It can also be
  12837. a Lisp form or a function that should be called at each matched headline, in
  12838. this case the return value is a list of all return values from these calls.
  12839. MATCHER is a function accepting three arguments, returning
  12840. a non-nil value whenever a given set of tags qualifies a headline
  12841. for inclusion. See `org-make-tags-matcher' for more information.
  12842. As a special case, it can also be set to t (respectively nil) in
  12843. order to match all (respectively none) headline.
  12844. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12845. keyword are included in the output.
  12846. START-LEVEL can be a string with asterisks, reducing the scope to
  12847. headlines matching this string."
  12848. (require 'org-agenda)
  12849. (let* ((re (concat "^"
  12850. (if start-level
  12851. ;; Get the correct level to match
  12852. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12853. org-outline-regexp)
  12854. " *\\(\\<\\("
  12855. (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
  12856. (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
  12857. (props (list 'face 'default
  12858. 'done-face 'org-agenda-done
  12859. 'undone-face 'default
  12860. 'mouse-face 'highlight
  12861. 'org-not-done-regexp org-not-done-regexp
  12862. 'org-todo-regexp org-todo-regexp
  12863. 'org-complex-heading-regexp org-complex-heading-regexp
  12864. 'help-echo
  12865. (format "mouse-2 or RET jump to org file %s"
  12866. (abbreviate-file-name
  12867. (or (buffer-file-name (buffer-base-buffer))
  12868. (buffer-name (buffer-base-buffer)))))))
  12869. (org-map-continue-from nil)
  12870. lspos tags tags-list
  12871. (tags-alist (list (cons 0 org-file-tags)))
  12872. (llast 0) rtn rtn1 level category i txt
  12873. todo marker entry priority
  12874. ts-date ts-date-type ts-date-pair)
  12875. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12876. (setq action (list 'lambda nil action)))
  12877. (save-excursion
  12878. (goto-char (point-min))
  12879. (when (eq action 'sparse-tree)
  12880. (org-overview)
  12881. (org-remove-occur-highlights))
  12882. (while (let (case-fold-search)
  12883. (re-search-forward re nil t))
  12884. (setq org-map-continue-from nil)
  12885. (catch :skip
  12886. (setq todo
  12887. ;; TODO: is the 1-2 difference a bug?
  12888. (when (match-end 1) (org-match-string-no-properties 2))
  12889. tags (when (match-end 4) (org-match-string-no-properties 4)))
  12890. (goto-char (setq lspos (match-beginning 0)))
  12891. (setq level (org-reduced-level (org-outline-level))
  12892. category (org-get-category))
  12893. (when (eq action 'agenda)
  12894. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12895. ts-date (car ts-date-pair)
  12896. ts-date-type (cdr ts-date-pair)))
  12897. (setq i llast llast level)
  12898. ;; remove tag lists from same and sublevels
  12899. (while (>= i level)
  12900. (when (setq entry (assoc i tags-alist))
  12901. (setq tags-alist (delete entry tags-alist)))
  12902. (setq i (1- i)))
  12903. ;; add the next tags
  12904. (when tags
  12905. (setq tags (org-split-string tags ":")
  12906. tags-alist
  12907. (cons (cons level tags) tags-alist)))
  12908. ;; compile tags for current headline
  12909. (setq tags-list
  12910. (if org-use-tag-inheritance
  12911. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12912. tags)
  12913. org-scanner-tags tags-list)
  12914. (when org-use-tag-inheritance
  12915. (setcdr (car tags-alist)
  12916. (mapcar (lambda (x)
  12917. (setq x (copy-sequence x))
  12918. (org-add-prop-inherited x))
  12919. (cdar tags-alist))))
  12920. (when (and tags org-use-tag-inheritance
  12921. (or (not (eq t org-use-tag-inheritance))
  12922. org-tags-exclude-from-inheritance))
  12923. ;; Selective inheritance, remove uninherited ones.
  12924. (setcdr (car tags-alist)
  12925. (org-remove-uninherited-tags (cdar tags-alist))))
  12926. (when (and
  12927. ;; eval matcher only when the todo condition is OK
  12928. (and (or (not todo-only) (member todo org-not-done-keywords))
  12929. (if (functionp matcher)
  12930. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12931. (funcall matcher todo tags-list level))
  12932. matcher))
  12933. ;; Call the skipper, but return t if it does not
  12934. ;; skip, so that the `and' form continues evaluating.
  12935. (progn
  12936. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12937. t)
  12938. ;; Check if timestamps are deselecting this entry
  12939. (or (not todo-only)
  12940. (and (member todo org-not-done-keywords)
  12941. (or (not org-agenda-tags-todo-honor-ignore-options)
  12942. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12943. ;; select this headline
  12944. (cond
  12945. ((eq action 'sparse-tree)
  12946. (and org-highlight-sparse-tree-matches
  12947. (org-get-heading) (match-end 0)
  12948. (org-highlight-new-match
  12949. (match-beginning 1) (match-end 1)))
  12950. (org-show-context 'tags-tree))
  12951. ((eq action 'agenda)
  12952. (setq txt (org-agenda-format-item
  12953. ""
  12954. (concat
  12955. (if (eq org-tags-match-list-sublevels 'indented)
  12956. (make-string (1- level) ?.) "")
  12957. (org-get-heading))
  12958. (make-string level ?\s)
  12959. category
  12960. tags-list)
  12961. priority (org-get-priority txt))
  12962. (goto-char lspos)
  12963. (setq marker (org-agenda-new-marker))
  12964. (org-add-props txt props
  12965. 'org-marker marker 'org-hd-marker marker 'org-category category
  12966. 'todo-state todo
  12967. 'ts-date ts-date
  12968. 'priority priority
  12969. 'type (concat "tagsmatch" ts-date-type))
  12970. (push txt rtn))
  12971. ((functionp action)
  12972. (setq org-map-continue-from nil)
  12973. (save-excursion
  12974. (setq rtn1 (funcall action))
  12975. (push rtn1 rtn)))
  12976. (t (user-error "Invalid action")))
  12977. ;; if we are to skip sublevels, jump to end of subtree
  12978. (unless org-tags-match-list-sublevels
  12979. (org-end-of-subtree t)
  12980. (backward-char 1))))
  12981. ;; Get the correct position from where to continue
  12982. (if org-map-continue-from
  12983. (goto-char org-map-continue-from)
  12984. (and (= (point) lspos) (end-of-line 1)))))
  12985. (when (and (eq action 'sparse-tree)
  12986. (not org-sparse-tree-open-archived-trees))
  12987. (org-hide-archived-subtrees (point-min) (point-max)))
  12988. (nreverse rtn)))
  12989. (defun org-remove-uninherited-tags (tags)
  12990. "Remove all tags that are not inherited from the list TAGS."
  12991. (cond
  12992. ((eq org-use-tag-inheritance t)
  12993. (if org-tags-exclude-from-inheritance
  12994. (org-delete-all org-tags-exclude-from-inheritance tags)
  12995. tags))
  12996. ((not org-use-tag-inheritance) nil)
  12997. ((stringp org-use-tag-inheritance)
  12998. (delq nil (mapcar
  12999. (lambda (x)
  13000. (if (and (string-match org-use-tag-inheritance x)
  13001. (not (member x org-tags-exclude-from-inheritance)))
  13002. x nil))
  13003. tags)))
  13004. ((listp org-use-tag-inheritance)
  13005. (delq nil (mapcar
  13006. (lambda (x)
  13007. (if (member x org-use-tag-inheritance) x nil))
  13008. tags)))))
  13009. (defun org-match-sparse-tree (&optional todo-only match)
  13010. "Create a sparse tree according to tags string MATCH.
  13011. MATCH can contain positive and negative selection of tags, like
  13012. \"+WORK+URGENT-WITHBOSS\".
  13013. If optional argument TODO-ONLY is non-nil, only select lines that are
  13014. also TODO lines."
  13015. (interactive "P")
  13016. (org-agenda-prepare-buffers (list (current-buffer)))
  13017. (let ((org--matcher-tags-todo-only todo-only))
  13018. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13019. org--matcher-tags-todo-only)))
  13020. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13021. (defvar org-cached-props nil)
  13022. (defun org-cached-entry-get (pom property)
  13023. (if (or (eq t org-use-property-inheritance)
  13024. (and (stringp org-use-property-inheritance)
  13025. (let ((case-fold-search t))
  13026. (org-string-match-p org-use-property-inheritance property)))
  13027. (and (listp org-use-property-inheritance)
  13028. (member-ignore-case property org-use-property-inheritance)))
  13029. ;; Caching is not possible, check it directly.
  13030. (org-entry-get pom property 'inherit)
  13031. ;; Get all properties, so we can do complicated checks easily.
  13032. (cdr (assoc-string property
  13033. (or org-cached-props
  13034. (setq org-cached-props (org-entry-properties pom)))
  13035. t))))
  13036. (defun org-global-tags-completion-table (&optional files)
  13037. "Return the list of all tags in all agenda buffer/files.
  13038. Optional FILES argument is a list of files which can be used
  13039. instead of the agenda files."
  13040. (save-excursion
  13041. (org-uniquify
  13042. (delq nil
  13043. (apply 'append
  13044. (mapcar
  13045. (lambda (file)
  13046. (set-buffer (find-file-noselect file))
  13047. (append (org-get-buffer-tags)
  13048. (mapcar (lambda (x) (if (stringp (car-safe x))
  13049. (list (car-safe x)) nil))
  13050. org-tag-alist)))
  13051. (if (and files (car files))
  13052. files
  13053. (org-agenda-files))))))))
  13054. (defun org-make-tags-matcher (match)
  13055. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13056. Returns a cons of the selection string MATCH and a function
  13057. implementing the matcher.
  13058. The matcher is to be called at an Org entry, with point on the
  13059. headline, and returns non-nil if the entry matches the selection
  13060. string MATCH. It must be called with three arguments: the TODO
  13061. keyword at the entry (or nil if none), the list of all tags at
  13062. the entry including inherited ones and the reduced level of the
  13063. headline. Additionally, the category of the entry, if any, must
  13064. be specified as the text property `org-category' on the headline.
  13065. This function sets the variable `org--matcher-tags-todo-only' to
  13066. a non-nil value if the matcher restricts matching to TODO
  13067. entries, otherwise it is not touched.
  13068. See also `org-scan-tags'."
  13069. (unless match
  13070. ;; Get a new match request, with completion against the global
  13071. ;; tags table and the local tags in current buffer.
  13072. (let ((org-last-tags-completion-table
  13073. (org-uniquify
  13074. (delq nil (append (org-get-buffer-tags)
  13075. (org-global-tags-completion-table))))))
  13076. (setq match
  13077. (completing-read
  13078. "Match: "
  13079. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13080. (let ((match0 match)
  13081. (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
  13082. (start 0)
  13083. tagsmatch todomatch tagsmatcher todomatcher)
  13084. ;; Expand group tags.
  13085. (setq match (org-tags-expand match))
  13086. ;; Check if there is a TODO part of this match, which would be the
  13087. ;; part after a "/". To make sure that this slash is not part of
  13088. ;; a property value to be matched against, we also check that
  13089. ;; there is no / after that slash. First, find the last slash.
  13090. (let ((s 0))
  13091. (while (string-match "/+" match s)
  13092. (setq start (match-beginning 0))
  13093. (setq s (match-end 0))))
  13094. (if (and (string-match "/+" match start)
  13095. (not (string-match-p "\"" match start)))
  13096. ;; Match contains also a TODO-matching request.
  13097. (progn
  13098. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13099. (setq todomatch (substring match (match-end 0)))
  13100. (when (string-match "\\`!" todomatch)
  13101. (setq org--matcher-tags-todo-only t)
  13102. (setq todomatch (substring todomatch 1)))
  13103. (when (string-match "\\`\\s-*\\'" todomatch)
  13104. (setq todomatch nil)))
  13105. ;; Only matching tags.
  13106. (setq tagsmatch match)
  13107. (setq todomatch nil))
  13108. ;; Make the tags matcher.
  13109. (if (not (org-string-nw-p tagsmatch))
  13110. (setq tagsmatcher t)
  13111. (let ((orlist nil)
  13112. (orterms (org-split-string tagsmatch "|"))
  13113. term)
  13114. (while (setq term (pop orterms))
  13115. (while (and (equal (substring term -1) "\\") orterms)
  13116. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13117. (while (string-match re term)
  13118. (let* ((rest (substring term (match-end 0)))
  13119. (minus (and (match-end 1)
  13120. (equal (match-string 1 term) "-")))
  13121. (tag (save-match-data
  13122. (replace-regexp-in-string
  13123. "\\\\-" "-" (match-string 2 term))))
  13124. (regexp (eq (string-to-char tag) ?{))
  13125. (levelp (match-end 4))
  13126. (propp (match-end 5))
  13127. (mm
  13128. (cond
  13129. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13130. (levelp
  13131. `(,(org-op-to-function (match-string 3 term))
  13132. level
  13133. ,(string-to-number (match-string 4 term))))
  13134. (propp
  13135. (let* ((gv (pcase (upcase (match-string 5 term))
  13136. ("CATEGORY"
  13137. '(get-text-property (point) 'org-category))
  13138. ("TODO" 'todo)
  13139. (p `(org-cached-entry-get nil ,p))))
  13140. (pv (match-string 7 term))
  13141. (regexp (eq (string-to-char pv) ?{))
  13142. (strp (eq (string-to-char pv) ?\"))
  13143. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13144. (po (org-op-to-function (match-string 6 term)
  13145. (if timep 'time strp))))
  13146. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13147. (when timep (setq pv (org-matcher-time pv)))
  13148. (cond ((and regexp (eq po 'org<>))
  13149. `(not (string-match ,pv (or ,gv ""))))
  13150. (regexp `(string-match ,pv (or ,gv "")))
  13151. (strp `(,po (or ,gv "") ,pv))
  13152. (t
  13153. `(,po
  13154. (string-to-number (or ,gv ""))
  13155. ,(string-to-number pv))))))
  13156. (t `(member ,tag tags-list)))))
  13157. (push (if minus `(not ,mm) mm) tagsmatcher)
  13158. (setq term rest)))
  13159. (push (if (> (length tagsmatcher) 1)
  13160. (cons 'and tagsmatcher)
  13161. (car tagsmatcher))
  13162. orlist)
  13163. (setq tagsmatcher nil))
  13164. (setq tagsmatcher
  13165. `(progn (setq org-cached-props nil) ,(cons 'or orlist)))))
  13166. ;; Make the TODO matcher.
  13167. (if (not (org-string-nw-p todomatch))
  13168. (setq todomatcher t)
  13169. (let ((orlist nil))
  13170. (dolist (term (org-split-string todomatch "|"))
  13171. (while (string-match re term)
  13172. (let* ((minus (and (match-end 1)
  13173. (equal (match-string 1 term) "-")))
  13174. (kwd (match-string 2 term))
  13175. (regexp (eq (string-to-char kwd) ?{))
  13176. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13177. `(equal todo ,kwd))))
  13178. (push (if minus `(not ,mm) mm) todomatcher))
  13179. (setq term (substring term (match-end 0))))
  13180. (push (if (> (length todomatcher) 1)
  13181. (cons 'and todomatcher)
  13182. (car todomatcher))
  13183. orlist)
  13184. (setq todomatcher nil))
  13185. (setq todomatcher (cons 'or orlist))))
  13186. ;; Return the string and function of the matcher.
  13187. (let ((matcher (if todomatcher `(and ,tagsmatcher ,todomatcher)
  13188. tagsmatcher)))
  13189. (when org--matcher-tags-todo-only
  13190. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13191. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13192. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13193. "Expand group tags in MATCH.
  13194. This replaces every group tag in MATCH with a regexp tag search.
  13195. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13196. will be replaced like this:
  13197. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13198. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13199. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13200. Replacing by a regexp preserves the structure of the match.
  13201. E.g., this expansion
  13202. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13203. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13204. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13205. A group tag in MATCH can contain regular expressions of its own.
  13206. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13207. will be replaced like this:
  13208. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13209. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13210. assumed to be a single group tag, and the function will return
  13211. the list of tags in this group.
  13212. When DOWNCASE is non-nil, expand downcased TAGS."
  13213. (if org-group-tags
  13214. (let* ((case-fold-search t)
  13215. (stable org-mode-syntax-table)
  13216. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13217. (taggroups (if downcased
  13218. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13219. taggroups)
  13220. taggroups))
  13221. (taggroups-keys (mapcar #'car taggroups))
  13222. (return-match (if downcased (downcase match) match))
  13223. (count 0)
  13224. (work-already-expanded tags-already-expanded)
  13225. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13226. ;; @ and _ are allowed as word-components in tags.
  13227. (modify-syntax-entry ?@ "w" stable)
  13228. (modify-syntax-entry ?_ "w" stable)
  13229. ;; Temporarily replace regexp-expressions in the match-expression.
  13230. (while (string-match "{.+?}" return-match)
  13231. (incf count)
  13232. (push (match-string 0 return-match) regexps-in-match)
  13233. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13234. (while (and taggroups-keys
  13235. (with-syntax-table stable
  13236. (string-match
  13237. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13238. (regexp-opt taggroups-keys) "\\>\\)")
  13239. return-match)))
  13240. (let* ((dir (match-string 1 return-match))
  13241. (tag (match-string 2 return-match))
  13242. (tag (if downcased (downcase tag) tag)))
  13243. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13244. (member tag work-already-expanded))
  13245. (setq tags-in-group (assoc tag taggroups))
  13246. (push tag work-already-expanded)
  13247. ;; Recursively expand each tag in the group, if the tag hasn't
  13248. ;; already been expanded. Restore the match-data after all recursive calls.
  13249. (save-match-data
  13250. (let (tags-expanded)
  13251. (dolist (x (cdr tags-in-group))
  13252. (if (and (member x taggroups-keys)
  13253. (not (member x work-already-expanded)))
  13254. (setq tags-expanded
  13255. (delete-dups
  13256. (append
  13257. (org-tags-expand x t downcased
  13258. work-already-expanded)
  13259. tags-expanded)))
  13260. (setq tags-expanded
  13261. (append (list x) tags-expanded)))
  13262. (setq work-already-expanded
  13263. (delete-dups
  13264. (append tags-expanded
  13265. work-already-expanded))))
  13266. (setq tags-in-group
  13267. (delete-dups (cons (car tags-in-group)
  13268. tags-expanded)))))
  13269. ;; Filter tag-regexps from tags.
  13270. (setq regexp-in-group-escaped
  13271. (delq nil (mapcar (lambda (x)
  13272. (if (stringp x)
  13273. (and (equal "{" (substring x 0 1))
  13274. (equal "}" (substring x -1))
  13275. x)
  13276. x))
  13277. tags-in-group))
  13278. regexp-in-group
  13279. (mapcar (lambda (x)
  13280. (substring x 1 -1))
  13281. regexp-in-group-escaped)
  13282. tags-in-group
  13283. (delq nil (mapcar (lambda (x)
  13284. (if (stringp x)
  13285. (and (not (equal "{" (substring x 0 1)))
  13286. (not (equal "}" (substring x -1)))
  13287. x)
  13288. x))
  13289. tags-in-group)))
  13290. ;; If single-as-list, do no more in the while-loop.
  13291. (if (not single-as-list)
  13292. (progn
  13293. (when regexp-in-group
  13294. (setq regexp-in-group
  13295. (concat "\\|"
  13296. (mapconcat 'identity regexp-in-group
  13297. "\\|"))))
  13298. (setq tags-in-group
  13299. (concat dir
  13300. "{\\<"
  13301. (regexp-opt tags-in-group)
  13302. "\\>"
  13303. regexp-in-group
  13304. "}"))
  13305. (when (stringp tags-in-group)
  13306. (org-add-props tags-in-group '(grouptag t)))
  13307. (setq return-match
  13308. (replace-match tags-in-group t t return-match)))
  13309. (setq tags-in-group
  13310. (append regexp-in-group-escaped tags-in-group))))
  13311. (setq taggroups-keys (delete tag taggroups-keys))))
  13312. ;; Add the regular expressions back into the match-expression again.
  13313. (while regexps-in-match
  13314. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13315. (pop regexps-in-match)
  13316. return-match t t))
  13317. (decf count))
  13318. (if single-as-list
  13319. (if tags-in-group tags-in-group (list return-match))
  13320. return-match))
  13321. (if single-as-list
  13322. (list (if downcased (downcase match) match))
  13323. match)))
  13324. (defun org-op-to-function (op &optional stringp)
  13325. "Turn an operator into the appropriate function."
  13326. (setq op
  13327. (cond
  13328. ((equal op "<" ) '(< string< org-time<))
  13329. ((equal op ">" ) '(> org-string> org-time>))
  13330. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13331. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13332. ((member op '("=" "==")) '(= string= org-time=))
  13333. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13334. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13335. (defun org<> (a b) (not (= a b)))
  13336. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13337. (defun org-string>= (a b) (not (string< a b)))
  13338. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13339. (defun org-string<> (a b) (not (string= a b)))
  13340. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13341. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13342. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13343. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13344. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13345. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13346. (defun org-2ft (s)
  13347. "Convert S to a floating point time.
  13348. If S is already a number, just return it. If it is a string, parse
  13349. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13350. (cond
  13351. ((numberp s) s)
  13352. ((stringp s)
  13353. (condition-case nil
  13354. (float-time (apply 'encode-time (org-parse-time-string s)))
  13355. (error 0.)))
  13356. (t 0.)))
  13357. (defun org-time-today ()
  13358. "Time in seconds today at 0:00.
  13359. Returns the float number of seconds since the beginning of the
  13360. epoch to the beginning of today (00:00)."
  13361. (float-time (apply 'encode-time
  13362. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13363. (defun org-matcher-time (s)
  13364. "Interpret a time comparison value."
  13365. (save-match-data
  13366. (cond
  13367. ((string= s "<now>") (float-time))
  13368. ((string= s "<today>") (org-time-today))
  13369. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13370. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13371. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13372. (+ (org-time-today)
  13373. (* (string-to-number (match-string 1 s))
  13374. (cdr (assoc (match-string 2 s)
  13375. '(("d" . 86400.0) ("w" . 604800.0)
  13376. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13377. (t (org-2ft s)))))
  13378. (defun org-match-any-p (re list)
  13379. "Does re match any element of list?"
  13380. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13381. (delq nil list))
  13382. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13383. (defvar org-tags-overlay (make-overlay 1 1))
  13384. (org-detach-overlay org-tags-overlay)
  13385. (defun org-get-local-tags-at (&optional pos)
  13386. "Get a list of tags defined in the current headline."
  13387. (org-get-tags-at pos 'local))
  13388. (defun org-get-local-tags ()
  13389. "Get a list of tags defined in the current headline."
  13390. (org-get-tags-at nil 'local))
  13391. (defun org-get-tags-at (&optional pos local)
  13392. "Get a list of all headline tags applicable at POS.
  13393. POS defaults to point. If tags are inherited, the list contains
  13394. the targets in the same sequence as the headlines appear, i.e.
  13395. the tags of the current headline come last.
  13396. When LOCAL is non-nil, only return tags from the current headline,
  13397. ignore inherited ones."
  13398. (interactive)
  13399. (if (and org-trust-scanner-tags
  13400. (or (not pos) (equal pos (point)))
  13401. (not local))
  13402. org-scanner-tags
  13403. (let (tags ltags lastpos parent)
  13404. (save-excursion
  13405. (save-restriction
  13406. (widen)
  13407. (goto-char (or pos (point)))
  13408. (save-match-data
  13409. (catch 'done
  13410. (condition-case nil
  13411. (progn
  13412. (org-back-to-heading t)
  13413. (while (not (equal lastpos (point)))
  13414. (setq lastpos (point))
  13415. (when (looking-at
  13416. (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13417. (setq ltags (org-split-string
  13418. (org-match-string-no-properties 1) ":"))
  13419. (when parent
  13420. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13421. (setq tags (append
  13422. (if parent
  13423. (org-remove-uninherited-tags ltags)
  13424. ltags)
  13425. tags)))
  13426. (or org-use-tag-inheritance (throw 'done t))
  13427. (when local (throw 'done t))
  13428. (or (org-up-heading-safe) (error nil))
  13429. (setq parent t)))
  13430. (error nil)))))
  13431. (if local
  13432. tags
  13433. (reverse (delete-dups
  13434. (reverse (append
  13435. (org-remove-uninherited-tags
  13436. org-file-tags)
  13437. tags)))))))))
  13438. (defun org-add-prop-inherited (s)
  13439. (add-text-properties 0 (length s) '(inherited t) s)
  13440. s)
  13441. (defun org-toggle-tag (tag &optional onoff)
  13442. "Toggle the tag TAG for the current line.
  13443. If ONOFF is `on' or `off', don't toggle but set to this state."
  13444. (let (res current)
  13445. (save-excursion
  13446. (org-back-to-heading t)
  13447. (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13448. (point-at-eol) t)
  13449. (progn
  13450. (setq current (match-string 1))
  13451. (replace-match ""))
  13452. (setq current ""))
  13453. (setq current (nreverse (org-split-string current ":")))
  13454. (cond
  13455. ((eq onoff 'on)
  13456. (setq res t)
  13457. (or (member tag current) (push tag current)))
  13458. ((eq onoff 'off)
  13459. (or (not (member tag current)) (setq current (delete tag current))))
  13460. (t (if (member tag current)
  13461. (setq current (delete tag current))
  13462. (setq res t)
  13463. (push tag current))))
  13464. (end-of-line 1)
  13465. (if current
  13466. (progn
  13467. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13468. (org-set-tags nil t))
  13469. (delete-horizontal-space))
  13470. (run-hooks 'org-after-tags-change-hook))
  13471. res))
  13472. (defun org-align-tags-here (to-col)
  13473. ;; Assumes that this is a headline
  13474. "Align tags on the current headline to TO-COL."
  13475. (let ((pos (point)) (col (current-column)) ncol tags-l p)
  13476. (beginning-of-line 1)
  13477. (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13478. (< pos (match-beginning 2)))
  13479. (progn
  13480. (setq tags-l (- (match-end 2) (match-beginning 2)))
  13481. (goto-char (match-beginning 1))
  13482. (insert " ")
  13483. (delete-region (point) (1+ (match-beginning 2)))
  13484. (setq ncol (max (current-column)
  13485. (1+ col)
  13486. (if (> to-col 0)
  13487. to-col
  13488. (- (abs to-col) tags-l))))
  13489. (setq p (point))
  13490. (insert (make-string (- ncol (current-column)) ?\ ))
  13491. (setq ncol (current-column))
  13492. (when indent-tabs-mode (tabify p (point-at-eol)))
  13493. (org-move-to-column (min ncol col)))
  13494. (goto-char pos))))
  13495. (defun org-set-tags-command (&optional arg just-align)
  13496. "Call the set-tags command for the current entry."
  13497. (interactive "P")
  13498. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13499. (org-set-tags arg just-align)
  13500. (save-excursion
  13501. (unless (and (org-region-active-p)
  13502. org-loop-over-headlines-in-active-region)
  13503. (org-back-to-heading t))
  13504. (org-set-tags arg just-align))))
  13505. (defun org-set-tags-to (data)
  13506. "Set the tags of the current entry to DATA, replacing the current tags.
  13507. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13508. If DATA is nil or the empty string, any tags will be removed."
  13509. (interactive "sTags: ")
  13510. (setq data
  13511. (cond
  13512. ((eq data nil) "")
  13513. ((equal data "") "")
  13514. ((stringp data)
  13515. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13516. ":"))
  13517. ((listp data)
  13518. (concat ":" (mapconcat 'identity data ":") ":"))))
  13519. (when data
  13520. (save-excursion
  13521. (org-back-to-heading t)
  13522. (when (looking-at org-complex-heading-regexp)
  13523. (if (match-end 5)
  13524. (progn
  13525. (goto-char (match-beginning 5))
  13526. (insert data)
  13527. (delete-region (point) (point-at-eol))
  13528. (org-set-tags nil 'align))
  13529. (goto-char (point-at-eol))
  13530. (insert " " data)
  13531. (org-set-tags nil 'align)))
  13532. (beginning-of-line 1)
  13533. (when (looking-at ".*?\\([ \t]+\\)$")
  13534. (delete-region (match-beginning 1) (match-end 1))))))
  13535. (defun org-align-all-tags ()
  13536. "Align the tags i all headings."
  13537. (interactive)
  13538. (save-excursion
  13539. (or (ignore-errors (org-back-to-heading t))
  13540. (outline-next-heading))
  13541. (if (org-at-heading-p)
  13542. (org-set-tags t)
  13543. (message "No headings"))))
  13544. (defvar org-indent-indentation-per-level)
  13545. (defun org-set-tags (&optional arg just-align)
  13546. "Set the tags for the current headline.
  13547. With prefix ARG, realign all tags in headings in the current buffer.
  13548. When JUST-ALIGN is non-nil, only align tags."
  13549. (interactive "P")
  13550. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13551. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13552. 'region-start-level
  13553. 'region))
  13554. org-loop-over-headlines-in-active-region)
  13555. (org-map-entries
  13556. ;; We don't use ARG and JUST-ALIGN here because these args
  13557. ;; are not useful when looping over headlines.
  13558. #'org-set-tags
  13559. org-loop-over-headlines-in-active-region
  13560. cl
  13561. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13562. (let ((org-setting-tags t))
  13563. (if arg
  13564. (save-excursion
  13565. (goto-char (point-min))
  13566. (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
  13567. (while (re-search-forward org-outline-regexp-bol nil t)
  13568. (org-set-tags nil t)
  13569. (end-of-line)))
  13570. (message "All tags realigned to column %d" org-tags-column))
  13571. (let* ((current (org-get-tags-string))
  13572. (col (current-column))
  13573. (tags
  13574. (if just-align current
  13575. ;; Get a new set of tags from the user.
  13576. (save-excursion
  13577. (let* ((table
  13578. (setq
  13579. org-last-tags-completion-table
  13580. (append
  13581. org-tag-persistent-alist
  13582. (or org-tag-alist (org-get-buffer-tags))
  13583. (and
  13584. org-complete-tags-always-offer-all-agenda-tags
  13585. (org-global-tags-completion-table
  13586. (org-agenda-files))))))
  13587. (current-tags (org-split-string current ":"))
  13588. (inherited-tags
  13589. (nreverse (nthcdr (length current-tags)
  13590. (nreverse (org-get-tags-at))))))
  13591. (replace-regexp-in-string
  13592. "\\([-+&]+\\|,\\)"
  13593. ":"
  13594. (if (or (eq t org-use-fast-tag-selection)
  13595. (and org-use-fast-tag-selection
  13596. (delq nil (mapcar #'cdr table))))
  13597. (org-fast-tag-selection
  13598. current-tags inherited-tags table
  13599. (and org-fast-tag-selection-include-todo
  13600. org-todo-key-alist))
  13601. (let ((org-add-colon-after-tag-completion
  13602. (< 1 (length table))))
  13603. (org-trim
  13604. (completing-read
  13605. "Tags: "
  13606. #'org-tags-completion-function
  13607. nil nil current 'org-tags-history))))))))))
  13608. (when org-tags-sort-function
  13609. (setq tags
  13610. (mapconcat
  13611. #'identity
  13612. (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
  13613. org-tags-sort-function)
  13614. ":")))
  13615. (if (not (org-string-nw-p tags)) (setq tags "")
  13616. (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
  13617. (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
  13618. ;; Insert new tags at the correct column
  13619. (beginning-of-line)
  13620. (let ((level (if (looking-at org-outline-regexp)
  13621. (- (match-end 0) (point) 1)
  13622. 1)))
  13623. (cond
  13624. ((and (equal current "") (equal tags "")))
  13625. ((re-search-forward
  13626. (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
  13627. (line-end-position)
  13628. t)
  13629. (if (equal tags "") (replace-match "" t t)
  13630. (goto-char (match-beginning 0))
  13631. (let* ((c0 (current-column))
  13632. ;; Compute offset for the case of org-indent-mode
  13633. ;; active.
  13634. (di (if (org-bound-and-true-p org-indent-mode)
  13635. (* (1- org-indent-indentation-per-level)
  13636. (1- level))
  13637. 0))
  13638. (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
  13639. (tc (+ org-tags-column
  13640. (if (> org-tags-column 0) (- di) di)))
  13641. (c1 (max (1+ c0)
  13642. (if (> tc 0) tc
  13643. (- (- tc) (string-width tags)))))
  13644. (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
  13645. (replace-match rpl t t)
  13646. (when (and (not (featurep 'xemacs)) indent-tabs-mode)
  13647. (tabify p0 (point))))))
  13648. (t (error "Tags alignment failed"))))
  13649. (org-move-to-column col))
  13650. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13651. (defun org-change-tag-in-region (beg end tag off)
  13652. "Add or remove TAG for each entry in the region.
  13653. This works in the agenda, and also in an org-mode buffer."
  13654. (interactive
  13655. (list (region-beginning) (region-end)
  13656. (let ((org-last-tags-completion-table
  13657. (if (derived-mode-p 'org-mode)
  13658. (org-uniquify
  13659. (delq nil (append (org-get-buffer-tags)
  13660. (org-global-tags-completion-table))))
  13661. (org-global-tags-completion-table))))
  13662. (completing-read
  13663. "Tag: " 'org-tags-completion-function nil nil nil
  13664. 'org-tags-history))
  13665. (progn
  13666. (message "[s]et or [r]emove? ")
  13667. (equal (read-char-exclusive) ?r))))
  13668. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13669. (let ((agendap (equal major-mode 'org-agenda-mode))
  13670. l1 l2 m buf pos newhead (cnt 0))
  13671. (goto-char end)
  13672. (setq l2 (1- (org-current-line)))
  13673. (goto-char beg)
  13674. (setq l1 (org-current-line))
  13675. (loop for l from l1 to l2 do
  13676. (org-goto-line l)
  13677. (setq m (get-text-property (point) 'org-hd-marker))
  13678. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13679. (and agendap m))
  13680. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13681. pos (if agendap m (point)))
  13682. (with-current-buffer buf
  13683. (save-excursion
  13684. (save-restriction
  13685. (goto-char pos)
  13686. (setq cnt (1+ cnt))
  13687. (org-toggle-tag tag (if off 'off 'on))
  13688. (setq newhead (org-get-heading)))))
  13689. (and agendap (org-agenda-change-all-lines newhead m))))
  13690. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13691. (defun org-tags-completion-function (string _predicate &optional flag)
  13692. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13693. (confirm (lambda (x) (stringp (car x)))))
  13694. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13695. (setq s1 (match-string 1 string)
  13696. s2 (match-string 2 string))
  13697. (setq s1 "" s2 string))
  13698. (cond
  13699. ((eq flag nil)
  13700. ;; try completion
  13701. (setq rtn (try-completion s2 ctable confirm))
  13702. (when (stringp rtn)
  13703. (setq rtn
  13704. (concat s1 s2 (substring rtn (length s2))
  13705. (if (and org-add-colon-after-tag-completion
  13706. (assoc rtn ctable))
  13707. ":" ""))))
  13708. rtn)
  13709. ((eq flag t)
  13710. ;; all-completions
  13711. (all-completions s2 ctable confirm))
  13712. ((eq flag 'lambda)
  13713. ;; exact match?
  13714. (assoc s2 ctable)))))
  13715. (defun org-fast-tag-insert (kwd tags face &optional end)
  13716. "Insert KDW, and the TAGS, the latter with face FACE.
  13717. Also insert END."
  13718. (insert (format "%-12s" (concat kwd ":"))
  13719. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13720. (or end "")))
  13721. (defun org-fast-tag-show-exit (flag)
  13722. (save-excursion
  13723. (org-goto-line 3)
  13724. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13725. (replace-match ""))
  13726. (when flag
  13727. (end-of-line 1)
  13728. (org-move-to-column (- (window-width) 19) t)
  13729. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13730. (defun org-set-current-tags-overlay (current prefix)
  13731. "Add an overlay to CURRENT tag with PREFIX."
  13732. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13733. (if (featurep 'xemacs)
  13734. (org-overlay-display org-tags-overlay (concat prefix s)
  13735. 'secondary-selection)
  13736. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13737. (org-overlay-display org-tags-overlay (concat prefix s)))))
  13738. (defvar org-last-tag-selection-key nil)
  13739. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13740. "Fast tag selection with single keys.
  13741. CURRENT is the current list of tags in the headline, INHERITED is the
  13742. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13743. possibly with grouping information. TODO-TABLE is a similar table with
  13744. TODO keywords, should these have keys assigned to them.
  13745. If the keys are nil, a-z are automatically assigned.
  13746. Returns the new tags string, or nil to not change the current settings."
  13747. (let* ((fulltable (append table todo-table))
  13748. (maxlen (apply 'max (mapcar
  13749. (lambda (x)
  13750. (if (stringp (car x)) (string-width (car x)) 0))
  13751. fulltable)))
  13752. (buf (current-buffer))
  13753. (expert (eq org-fast-tag-selection-single-key 'expert))
  13754. (buffer-tags nil)
  13755. (fwidth (+ maxlen 3 1 3))
  13756. (ncol (/ (- (window-width) 4) fwidth))
  13757. (i-face 'org-done)
  13758. (c-face 'org-todo)
  13759. tg cnt e c char c1 c2 ntable tbl rtn
  13760. ov-start ov-end ov-prefix
  13761. (exit-after-next org-fast-tag-selection-single-key)
  13762. (done-keywords org-done-keywords)
  13763. groups ingroup intaggroup)
  13764. (save-excursion
  13765. (beginning-of-line 1)
  13766. (if (looking-at
  13767. (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13768. (setq ov-start (match-beginning 1)
  13769. ov-end (match-end 1)
  13770. ov-prefix "")
  13771. (setq ov-start (1- (point-at-eol))
  13772. ov-end (1+ ov-start))
  13773. (skip-chars-forward "^\n\r")
  13774. (setq ov-prefix
  13775. (concat
  13776. (buffer-substring (1- (point)) (point))
  13777. (if (> (current-column) org-tags-column)
  13778. " "
  13779. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13780. (move-overlay org-tags-overlay ov-start ov-end)
  13781. (save-window-excursion
  13782. (if expert
  13783. (set-buffer (get-buffer-create " *Org tags*"))
  13784. (delete-other-windows)
  13785. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13786. (org-switch-to-buffer-other-window " *Org tags*"))
  13787. (erase-buffer)
  13788. (setq-local org-done-keywords done-keywords)
  13789. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13790. (org-fast-tag-insert "Current" current c-face "\n\n")
  13791. (org-fast-tag-show-exit exit-after-next)
  13792. (org-set-current-tags-overlay current ov-prefix)
  13793. (setq tbl fulltable char ?a cnt 0)
  13794. (while (setq e (pop tbl))
  13795. (cond
  13796. ((eq (car e) :startgroup)
  13797. (push '() groups) (setq ingroup t)
  13798. (unless (zerop cnt)
  13799. (setq cnt 0)
  13800. (insert "\n"))
  13801. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13802. ((eq (car e) :endgroup)
  13803. (setq ingroup nil cnt 0)
  13804. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13805. ((eq (car e) :startgrouptag)
  13806. (setq intaggroup t)
  13807. (unless (zerop cnt)
  13808. (setq cnt 0)
  13809. (insert "\n"))
  13810. (insert "[ "))
  13811. ((eq (car e) :endgrouptag)
  13812. (setq intaggroup nil cnt 0)
  13813. (insert "]\n"))
  13814. ((equal e '(:newline))
  13815. (unless (zerop cnt)
  13816. (setq cnt 0)
  13817. (insert "\n")
  13818. (setq e (car tbl))
  13819. (while (equal (car tbl) '(:newline))
  13820. (insert "\n")
  13821. (setq tbl (cdr tbl)))))
  13822. ((equal e '(:grouptags)) (insert " : "))
  13823. (t
  13824. (setq tg (copy-sequence (car e)) c2 nil)
  13825. (if (cdr e)
  13826. (setq c (cdr e))
  13827. ;; automatically assign a character.
  13828. (setq c1 (string-to-char
  13829. (downcase (substring
  13830. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13831. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13832. (while (or (rassoc char ntable) (rassoc char table))
  13833. (setq char (1+ char)))
  13834. (setq c2 c1))
  13835. (setq c (or c2 char)))
  13836. (when ingroup (push tg (car groups)))
  13837. (setq tg (org-add-props tg nil 'face
  13838. (cond
  13839. ((not (assoc tg table))
  13840. (org-get-todo-face tg))
  13841. ((member tg current) c-face)
  13842. ((member tg inherited) i-face))))
  13843. (when (equal (caar tbl) :grouptags)
  13844. (org-add-props tg nil 'face 'org-tag-group))
  13845. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13846. (insert "[" c "] " tg (make-string
  13847. (- fwidth 4 (length tg)) ?\ ))
  13848. (push (cons tg c) ntable)
  13849. (when (= (incf cnt) ncol)
  13850. (insert "\n")
  13851. (when (or ingroup intaggroup) (insert " "))
  13852. (setq cnt 0)))))
  13853. (setq ntable (nreverse ntable))
  13854. (insert "\n")
  13855. (goto-char (point-min))
  13856. (unless expert (org-fit-window-to-buffer))
  13857. (setq rtn
  13858. (catch 'exit
  13859. (while t
  13860. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13861. (if (not groups) "no " "")
  13862. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13863. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13864. (setq org-last-tag-selection-key c)
  13865. (cond
  13866. ((= c ?\r) (throw 'exit t))
  13867. ((= c ?!)
  13868. (setq groups (not groups))
  13869. (goto-char (point-min))
  13870. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13871. ((= c ?\C-c)
  13872. (if (not expert)
  13873. (org-fast-tag-show-exit
  13874. (setq exit-after-next (not exit-after-next)))
  13875. (setq expert nil)
  13876. (delete-other-windows)
  13877. (set-window-buffer (split-window-vertically) " *Org tags*")
  13878. (org-switch-to-buffer-other-window " *Org tags*")
  13879. (org-fit-window-to-buffer)))
  13880. ((or (= c ?\C-g)
  13881. (and (= c ?q) (not (rassoc c ntable))))
  13882. (org-detach-overlay org-tags-overlay)
  13883. (setq quit-flag t))
  13884. ((= c ?\ )
  13885. (setq current nil)
  13886. (when exit-after-next (setq exit-after-next 'now)))
  13887. ((= c ?\t)
  13888. (condition-case nil
  13889. (setq tg (completing-read
  13890. "Tag: "
  13891. (or buffer-tags
  13892. (with-current-buffer buf
  13893. (setq buffer-tags
  13894. (org-get-buffer-tags))))))
  13895. (quit (setq tg "")))
  13896. (when (string-match "\\S-" tg)
  13897. (add-to-list 'buffer-tags (list tg))
  13898. (if (member tg current)
  13899. (setq current (delete tg current))
  13900. (push tg current)))
  13901. (when exit-after-next (setq exit-after-next 'now)))
  13902. ((setq e (rassoc c todo-table) tg (car e))
  13903. (with-current-buffer buf
  13904. (save-excursion (org-todo tg)))
  13905. (when exit-after-next (setq exit-after-next 'now)))
  13906. ((setq e (rassoc c ntable) tg (car e))
  13907. (if (member tg current)
  13908. (setq current (delete tg current))
  13909. (loop for g in groups do
  13910. (when (member tg g)
  13911. (dolist (x g) (setq current (delete x current)))))
  13912. (push tg current))
  13913. (when exit-after-next (setq exit-after-next 'now))))
  13914. ;; Create a sorted list
  13915. (setq current
  13916. (sort current
  13917. (lambda (a b)
  13918. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13919. (when (eq exit-after-next 'now) (throw 'exit t))
  13920. (goto-char (point-min))
  13921. (beginning-of-line 2)
  13922. (delete-region (point) (point-at-eol))
  13923. (org-fast-tag-insert "Current" current c-face)
  13924. (org-set-current-tags-overlay current ov-prefix)
  13925. (while (re-search-forward
  13926. (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
  13927. (setq tg (match-string 1))
  13928. (add-text-properties
  13929. (match-beginning 1) (match-end 1)
  13930. (list 'face
  13931. (cond
  13932. ((member tg current) c-face)
  13933. ((member tg inherited) i-face)
  13934. (t (get-text-property (match-beginning 1) 'face))))))
  13935. (goto-char (point-min)))))
  13936. (org-detach-overlay org-tags-overlay)
  13937. (if rtn
  13938. (mapconcat 'identity current ":")
  13939. nil))))
  13940. (defun org-get-tags-string ()
  13941. "Get the TAGS string in the current headline."
  13942. (unless (org-at-heading-p t)
  13943. (user-error "Not on a heading"))
  13944. (save-excursion
  13945. (beginning-of-line 1)
  13946. (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13947. (org-match-string-no-properties 1)
  13948. "")))
  13949. (defun org-get-tags ()
  13950. "Get the list of tags specified in the current headline."
  13951. (org-split-string (org-get-tags-string) ":"))
  13952. (defun org-get-buffer-tags ()
  13953. "Get a table of all tags used in the buffer, for completion."
  13954. (org-with-wide-buffer
  13955. (goto-char (point-min))
  13956. (let ((tag-re (concat org-outline-regexp-bol
  13957. "\\(?:.*?[ \t]\\)?"
  13958. (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
  13959. tags)
  13960. (while (re-search-forward tag-re nil t)
  13961. (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
  13962. (push tag tags)))
  13963. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13964. ;;;; The mapping API
  13965. (defun org-map-entries (func &optional match scope &rest skip)
  13966. "Call FUNC at each headline selected by MATCH in SCOPE.
  13967. FUNC is a function or a lisp form. The function will be called without
  13968. arguments, with the cursor positioned at the beginning of the headline.
  13969. The return values of all calls to the function will be collected and
  13970. returned as a list.
  13971. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13972. does not need to preserve point. After evaluation, the cursor will be
  13973. moved to the end of the line (presumably of the headline of the
  13974. processed entry) and search continues from there. Under some
  13975. circumstances, this may not produce the wanted results. For example,
  13976. if you have removed (e.g. archived) the current (sub)tree it could
  13977. mean that the next entry will be skipped entirely. In such cases, you
  13978. can specify the position from where search should continue by making
  13979. FUNC set the variable `org-map-continue-from' to the desired buffer
  13980. position.
  13981. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13982. Only headlines that are matched by this query will be considered during
  13983. the iteration. When MATCH is nil or t, all headlines will be
  13984. visited by the iteration.
  13985. SCOPE determines the scope of this command. It can be any of:
  13986. nil The current buffer, respecting the restriction if any
  13987. tree The subtree started with the entry at point
  13988. region The entries within the active region, if any
  13989. region-start-level
  13990. The entries within the active region, but only those at
  13991. the same level than the first one.
  13992. file The current buffer, without restriction
  13993. file-with-archives
  13994. The current buffer, and any archives associated with it
  13995. agenda All agenda files
  13996. agenda-with-archives
  13997. All agenda files with any archive files associated with them
  13998. \(file1 file2 ...)
  13999. If this is a list, all files in the list will be scanned
  14000. The remaining args are treated as settings for the skipping facilities of
  14001. the scanner. The following items can be given here:
  14002. archive skip trees with the archive tag
  14003. comment skip trees with the COMMENT keyword
  14004. function or Emacs Lisp form:
  14005. will be used as value for `org-agenda-skip-function', so
  14006. whenever the function returns a position, FUNC will not be
  14007. called for that entry and search will continue from the
  14008. position returned
  14009. If your function needs to retrieve the tags including inherited tags
  14010. at the *current* entry, you can use the value of the variable
  14011. `org-scanner-tags' which will be much faster than getting the value
  14012. with `org-get-tags-at'. If your function gets properties with
  14013. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14014. to t around the call to `org-entry-properties' to get the same speedup.
  14015. Note that if your function moves around to retrieve tags and properties at
  14016. a *different* entry, you cannot use these techniques."
  14017. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14018. (not (org-region-active-p)))
  14019. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14020. (org-agenda-skip-archived-trees (memq 'archive skip))
  14021. (org-agenda-skip-comment-trees (memq 'comment skip))
  14022. (org-agenda-skip-function
  14023. (car (org-delete-all '(comment archive) skip)))
  14024. (org-tags-match-list-sublevels t)
  14025. (start-level (eq scope 'region-start-level))
  14026. matcher res
  14027. org-todo-keywords-for-agenda
  14028. org-done-keywords-for-agenda
  14029. org-todo-keyword-alist-for-agenda
  14030. org-tag-alist-for-agenda
  14031. org--matcher-tags-todo-only)
  14032. (cond
  14033. ((eq match t) (setq matcher t))
  14034. ((eq match nil) (setq matcher t))
  14035. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14036. (save-excursion
  14037. (save-restriction
  14038. (cond ((eq scope 'tree)
  14039. (org-back-to-heading t)
  14040. (org-narrow-to-subtree)
  14041. (setq scope nil))
  14042. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14043. (org-region-active-p))
  14044. ;; If needed, set start-level to a string like "2"
  14045. (when start-level
  14046. (save-excursion
  14047. (goto-char (region-beginning))
  14048. (unless (org-at-heading-p) (outline-next-heading))
  14049. (setq start-level (org-current-level))))
  14050. (narrow-to-region (region-beginning)
  14051. (save-excursion
  14052. (goto-char (region-end))
  14053. (unless (and (bolp) (org-at-heading-p))
  14054. (outline-next-heading))
  14055. (point)))
  14056. (setq scope nil)))
  14057. (if (not scope)
  14058. (progn
  14059. (org-agenda-prepare-buffers
  14060. (and buffer-file-name (list buffer-file-name)))
  14061. (setq res
  14062. (org-scan-tags
  14063. func matcher org--matcher-tags-todo-only start-level)))
  14064. ;; Get the right scope
  14065. (cond
  14066. ((and scope (listp scope) (symbolp (car scope)))
  14067. (setq scope (eval scope)))
  14068. ((eq scope 'agenda)
  14069. (setq scope (org-agenda-files t)))
  14070. ((eq scope 'agenda-with-archives)
  14071. (setq scope (org-agenda-files t))
  14072. (setq scope (org-add-archive-files scope)))
  14073. ((eq scope 'file)
  14074. (setq scope (and buffer-file-name (list buffer-file-name))))
  14075. ((eq scope 'file-with-archives)
  14076. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14077. (org-agenda-prepare-buffers scope)
  14078. (dolist (file scope)
  14079. (with-current-buffer (org-find-base-buffer-visiting file)
  14080. (save-excursion
  14081. (save-restriction
  14082. (widen)
  14083. (goto-char (point-min))
  14084. (setq res
  14085. (append
  14086. res
  14087. (org-scan-tags
  14088. func matcher org--matcher-tags-todo-only))))))))))
  14089. res)))
  14090. ;;; Properties API
  14091. (defconst org-special-properties
  14092. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14093. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14094. "The special properties valid in Org mode.
  14095. These are properties that are not defined in the property drawer,
  14096. but in some other way.")
  14097. (defconst org-default-properties
  14098. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14099. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14100. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14101. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14102. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14103. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14104. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14105. "Some properties that are used by Org mode for various purposes.
  14106. Being in this list makes sure that they are offered for completion.")
  14107. (defun org--valid-property-p (property)
  14108. "Non nil when string PROPERTY is a valid property name."
  14109. (not
  14110. (or (equal property "")
  14111. (org-string-match-p "\\s-" property))))
  14112. (defun org--update-property-plist (key val props)
  14113. "Associate KEY to VAL in alist PROPS.
  14114. Modifications are made by side-effect. Return new alist."
  14115. (let* ((appending (string= (substring key -1) "+"))
  14116. (key (if appending (substring key 0 -1) key))
  14117. (old (assoc-string key props t)))
  14118. (if (not old) (cons (cons key val) props)
  14119. (setcdr old (if appending (concat (cdr old) " " val) val))
  14120. props)))
  14121. (defun org-get-property-block (&optional beg force)
  14122. "Return the (beg . end) range of the body of the property drawer.
  14123. BEG is the beginning of the current subtree, or of the part
  14124. before the first headline. If it is not given, it will be found.
  14125. If the drawer does not exist, create it if FORCE is non-nil, or
  14126. return nil."
  14127. (org-with-wide-buffer
  14128. (when beg (goto-char beg))
  14129. (unless (org-before-first-heading-p)
  14130. (let ((beg (cond (beg)
  14131. ((or (not (featurep 'org-inlinetask))
  14132. (org-inlinetask-in-task-p))
  14133. (org-back-to-heading t))
  14134. (t (org-with-limited-levels (org-back-to-heading t))))))
  14135. (forward-line)
  14136. (when (org-looking-at-p org-planning-line-re) (forward-line))
  14137. (cond ((looking-at org-property-drawer-re)
  14138. (forward-line)
  14139. (cons (point) (progn (goto-char (match-end 0))
  14140. (line-beginning-position))))
  14141. (force
  14142. (goto-char beg)
  14143. (org-insert-property-drawer)
  14144. (let ((pos (save-excursion (search-forward ":END:")
  14145. (line-beginning-position))))
  14146. (cons pos pos))))))))
  14147. (defun org-at-property-p ()
  14148. "Non-nil when point is inside a property drawer.
  14149. See `org-property-re' for match data, if applicable."
  14150. (save-excursion
  14151. (beginning-of-line)
  14152. (and (looking-at org-property-re)
  14153. (let ((property-drawer (save-match-data (org-get-property-block))))
  14154. (and property-drawer
  14155. (>= (point) (car property-drawer))
  14156. (< (point) (cdr property-drawer)))))))
  14157. (defun org-property-action ()
  14158. "Do an action on properties."
  14159. (interactive)
  14160. (unless (org-at-property-p) (user-error "Not at a property"))
  14161. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14162. (let ((c (read-char-exclusive)))
  14163. (case c
  14164. (?s (call-interactively #'org-set-property))
  14165. (?d (call-interactively #'org-delete-property))
  14166. (?D (call-interactively #'org-delete-property-globally))
  14167. (?c (call-interactively #'org-compute-property-at-point))
  14168. (otherwise (user-error "No such property action %c" c)))))
  14169. (defun org-inc-effort ()
  14170. "Increment the value of the effort property in the current entry."
  14171. (interactive)
  14172. (org-set-effort nil t))
  14173. (defvar org-clock-effort) ; Defined in org-clock.el.
  14174. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14175. (defun org-set-effort (&optional value increment)
  14176. "Set the effort property of the current entry.
  14177. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14178. 10th allowed value.
  14179. When INCREMENT is non-nil, set the property to the next allowed value."
  14180. (interactive "P")
  14181. (when (equal value 0) (setq value 10))
  14182. (let* ((completion-ignore-case t)
  14183. (prop org-effort-property)
  14184. (cur (org-entry-get nil prop))
  14185. (allowed (org-property-get-allowed-values nil prop 'table))
  14186. (existing (mapcar 'list (org-property-values prop)))
  14187. (heading (nth 4 (org-heading-components)))
  14188. rpl
  14189. (val (cond
  14190. ((stringp value) value)
  14191. ((and allowed (integerp value))
  14192. (or (car (nth (1- value) allowed))
  14193. (car (org-last allowed))))
  14194. ((and allowed increment)
  14195. (or (caadr (member (list cur) allowed))
  14196. (user-error "Allowed effort values are not set")))
  14197. (allowed
  14198. (message "Select 1-9,0, [RET%s]: %s"
  14199. (if cur (concat "=" cur) "")
  14200. (mapconcat 'car allowed " "))
  14201. (setq rpl (read-char-exclusive))
  14202. (if (equal rpl ?\r)
  14203. cur
  14204. (setq rpl (- rpl ?0))
  14205. (when (equal rpl 0) (setq rpl 10))
  14206. (if (and (> rpl 0) (<= rpl (length allowed)))
  14207. (car (nth (1- rpl) allowed))
  14208. (org-completing-read "Effort: " allowed nil))))
  14209. (t
  14210. (let (org-completion-use-ido org-completion-use-iswitchb)
  14211. (org-completing-read
  14212. (concat "Effort " (if (and cur (string-match "\\S-" cur))
  14213. (concat "[" cur "]") "")
  14214. ": ")
  14215. existing nil nil "" nil cur))))))
  14216. (unless (equal (org-entry-get nil prop) val)
  14217. (org-entry-put nil prop val))
  14218. (org-refresh-property
  14219. '((effort . identity)
  14220. (effort-minutes . org-duration-string-to-minutes))
  14221. val)
  14222. (when (string= heading org-clock-current-task)
  14223. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14224. (org-clock-update-mode-line))
  14225. (message "%s is now %s" prop val)))
  14226. (defun org-entry-properties (&optional pom which)
  14227. "Get all properties of the current entry.
  14228. When POM is a buffer position, get all properties from the entry
  14229. there instead.
  14230. This includes the TODO keyword, the tags, time strings for
  14231. deadline, scheduled, and clocking, and any additional properties
  14232. defined in the entry.
  14233. If WHICH is nil or `all', get all properties. If WHICH is
  14234. `special' or `standard', only get that subclass. If WHICH is
  14235. a string, only get that property.
  14236. Return value is an alist. Keys are properties, as upcased
  14237. strings."
  14238. (org-with-point-at pom
  14239. (when (and (derived-mode-p 'org-mode)
  14240. (ignore-errors (org-back-to-heading t)))
  14241. (catch 'exit
  14242. (let* ((beg (point))
  14243. (specific (and (stringp which) (upcase which)))
  14244. (which (cond ((not specific) which)
  14245. ((member specific org-special-properties) 'special)
  14246. (t 'standard)))
  14247. props)
  14248. ;; Get the special properties, like TODO and TAGS.
  14249. (when (memq which '(nil all special))
  14250. (when (or (not specific) (string= specific "CLOCKSUM"))
  14251. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14252. (when clocksum
  14253. (push (cons "CLOCKSUM"
  14254. (org-columns-number-to-string
  14255. (/ (float clocksum) 60.) 'add_times))
  14256. props)))
  14257. (when specific (throw 'exit props)))
  14258. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14259. (let ((clocksumt (get-text-property (point)
  14260. :org-clock-minutes-today)))
  14261. (when clocksumt
  14262. (push (cons "CLOCKSUM_T"
  14263. (org-columns-number-to-string
  14264. (/ (float clocksumt) 60.) 'add_times))
  14265. props)))
  14266. (when specific (throw 'exit props)))
  14267. (when (or (not specific) (string= specific "ITEM"))
  14268. (when (looking-at org-complex-heading-regexp)
  14269. (push (cons "ITEM"
  14270. (concat
  14271. (org-match-string-no-properties 1)
  14272. (let ((title (org-match-string-no-properties 4)))
  14273. (when (org-string-nw-p title)
  14274. (concat " " (org-remove-tabs title))))))
  14275. props))
  14276. (when specific (throw 'exit props)))
  14277. (when (or (not specific) (string= specific "TODO"))
  14278. (let ((case-fold-search nil))
  14279. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14280. (push (cons "TODO" (org-match-string-no-properties 2)) props)))
  14281. (when specific (throw 'exit props)))
  14282. (when (or (not specific) (string= specific "PRIORITY"))
  14283. (push (cons "PRIORITY"
  14284. (if (looking-at org-priority-regexp)
  14285. (org-match-string-no-properties 2)
  14286. (char-to-string org-default-priority)))
  14287. props)
  14288. (when specific (throw 'exit props)))
  14289. (when (or (not specific) (string= specific "FILE"))
  14290. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14291. props)
  14292. (when specific (throw 'exit props)))
  14293. (when (or (not specific) (string= specific "TAGS"))
  14294. (let ((value (org-string-nw-p (org-get-tags-string))))
  14295. (when value (push (cons "TAGS" value) props)))
  14296. (when specific (throw 'exit props)))
  14297. (when (or (not specific) (string= specific "ALLTAGS"))
  14298. (let ((value (org-get-tags-at)))
  14299. (when value
  14300. (push (cons "ALLTAGS"
  14301. (format ":%s:" (mapconcat #'identity value ":")))
  14302. props)))
  14303. (when specific (throw 'exit props)))
  14304. (when (or (not specific) (string= specific "BLOCKED"))
  14305. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14306. (when specific (throw 'exit props)))
  14307. (when (or (not specific)
  14308. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14309. (forward-line)
  14310. (when (org-looking-at-p org-planning-line-re)
  14311. (end-of-line)
  14312. (let ((bol (line-beginning-position))
  14313. ;; Backward compatibility: time keywords used to
  14314. ;; be configurable (before 8.3). Make sure we
  14315. ;; get the correct keyword.
  14316. (key-assoc `(("CLOSED" . ,org-closed-string)
  14317. ("DEADLINE" . ,org-deadline-string)
  14318. ("SCHEDULED" . ,org-scheduled-string))))
  14319. (dolist (pair (if specific (list (assoc specific key-assoc))
  14320. key-assoc))
  14321. (save-excursion
  14322. (when (search-backward (cdr pair) bol t)
  14323. (goto-char (match-end 0))
  14324. (skip-chars-forward " \t")
  14325. (and (looking-at org-ts-regexp-both)
  14326. (push (cons (car pair)
  14327. (org-match-string-no-properties 0))
  14328. props)))))))
  14329. (when specific (throw 'exit props)))
  14330. (when (or (not specific)
  14331. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14332. (let ((find-ts
  14333. (lambda (end ts)
  14334. ;; Fix next time-stamp before END. TS is the
  14335. ;; list of time-stamps found so far.
  14336. (let ((ts ts)
  14337. (regexp (cond
  14338. ((string= specific "TIMESTAMP")
  14339. org-ts-regexp)
  14340. ((string= specific "TIMESTAMP_IA")
  14341. org-ts-regexp-inactive)
  14342. ((assoc "TIMESTAMP_IA" ts)
  14343. org-ts-regexp)
  14344. ((assoc "TIMESTAMP" ts)
  14345. org-ts-regexp-inactive)
  14346. (t org-ts-regexp-both))))
  14347. (catch 'next
  14348. (while (re-search-forward regexp end t)
  14349. (backward-char)
  14350. (let ((object (org-element-context)))
  14351. ;; Accept to match timestamps in node
  14352. ;; properties, too.
  14353. (when (memq (org-element-type object)
  14354. '(node-property timestamp))
  14355. (let ((type
  14356. (org-element-property :type object)))
  14357. (cond
  14358. ((and (memq type '(active active-range))
  14359. (not (equal specific "TIMESTAMP_IA")))
  14360. (unless (assoc "TIMESTAMP" ts)
  14361. (push (cons "TIMESTAMP"
  14362. (org-element-property
  14363. :raw-value object))
  14364. ts)
  14365. (when specific (throw 'exit ts))))
  14366. ((and (memq type '(inactive inactive-range))
  14367. (not (string= specific "TIMESTAMP")))
  14368. (unless (assoc "TIMESTAMP_IA" ts)
  14369. (push (cons "TIMESTAMP_IA"
  14370. (org-element-property
  14371. :raw-value object))
  14372. ts)
  14373. (when specific (throw 'exit ts))))))
  14374. ;; Both timestamp types are found,
  14375. ;; move to next part.
  14376. (when (= (length ts) 2) (throw 'next ts)))))
  14377. ts)))))
  14378. (goto-char beg)
  14379. ;; First look for timestamps within headline.
  14380. (let ((ts (funcall find-ts (line-end-position) nil)))
  14381. (if (= (length ts) 2) (setq props (nconc ts props))
  14382. (forward-line)
  14383. ;; Then find timestamps in the section, skipping
  14384. ;; planning line.
  14385. (when (org-looking-at-p org-planning-line-re)
  14386. (forward-line))
  14387. (let ((end (save-excursion (outline-next-heading))))
  14388. (setq props (nconc (funcall find-ts end ts) props))))))))
  14389. ;; Get the standard properties, like :PROP:.
  14390. (when (memq which '(nil all standard))
  14391. ;; If we are looking after a specific property, delegate
  14392. ;; to `org-entry-get', which is faster. However, make an
  14393. ;; exception for "CATEGORY", since it can be also set
  14394. ;; through keywords (i.e. #+CATEGORY).
  14395. (if (and specific (not (equal specific "CATEGORY")))
  14396. (let ((value (org-entry-get beg specific nil t)))
  14397. (throw 'exit (and value (list (cons specific value)))))
  14398. (let ((range (org-get-property-block beg)))
  14399. (when range
  14400. (let ((end (cdr range)) seen-base)
  14401. (goto-char (car range))
  14402. ;; Unlike to `org--update-property-plist', we
  14403. ;; handle the case where base values is found
  14404. ;; after its extension. We also forbid standard
  14405. ;; properties to be named as special properties.
  14406. (while (re-search-forward org-property-re end t)
  14407. (let* ((key (upcase (org-match-string-no-properties 2)))
  14408. (extendp (org-string-match-p "\\+\\'" key))
  14409. (key-base (if extendp (substring key 0 -1) key))
  14410. (value (org-match-string-no-properties 3)))
  14411. (cond
  14412. ((member-ignore-case key-base org-special-properties))
  14413. (extendp
  14414. (setq props
  14415. (org--update-property-plist key value props)))
  14416. ((member key seen-base))
  14417. (t (push key seen-base)
  14418. (let ((p (assoc-string key props t)))
  14419. (if p (setcdr p (concat value " " (cdr p)))
  14420. (push (cons key value) props))))))))))))
  14421. (unless (assoc "CATEGORY" props)
  14422. (push (cons "CATEGORY" (org-get-category beg)) props)
  14423. (when (string= specific "CATEGORY") (throw 'exit props)))
  14424. ;; Return value.
  14425. props)))))
  14426. (defun org-property--local-values (property literal-nil)
  14427. "Return value for PROPERTY in current entry.
  14428. Value is a list whose care is the base value for PROPERTY and cdr
  14429. a list of accumulated values. Return nil if neither is found in
  14430. the entry. Also return nil when PROPERTY is set to \"nil\",
  14431. unless LITERAL-NIL is non-nil."
  14432. (let ((range (org-get-property-block)))
  14433. (when range
  14434. (goto-char (car range))
  14435. (let* ((case-fold-search t)
  14436. (end (cdr range))
  14437. (value
  14438. ;; Base value.
  14439. (save-excursion
  14440. (let ((v (and (re-search-forward
  14441. (org-re-property property nil t) end t)
  14442. (org-match-string-no-properties 3))))
  14443. (list (if literal-nil v (org-not-nil v)))))))
  14444. ;; Find additional values.
  14445. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14446. (while (re-search-forward property+ end t)
  14447. (push (org-match-string-no-properties 3) value)))
  14448. ;; Return final values.
  14449. (and (not (equal value '(nil))) (nreverse value))))))
  14450. (defun org-entry-get (pom property &optional inherit literal-nil)
  14451. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14452. If INHERIT is non-nil and the entry does not have the property,
  14453. then also check higher levels of the hierarchy. If INHERIT is
  14454. the symbol `selective', use inheritance only if the setting in
  14455. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14456. If the property is present but empty, the return value is the
  14457. empty string. If the property is not present at all, nil is
  14458. returned. In any other case, return the value as a string.
  14459. Search is case-insensitive.
  14460. If LITERAL-NIL is set, return the string value \"nil\" as
  14461. a string, do not interpret it as the list atom nil. This is used
  14462. for inheritance when a \"nil\" value can supersede a non-nil
  14463. value higher up the hierarchy."
  14464. (org-with-point-at pom
  14465. (cond
  14466. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14467. ;; We need a special property. Use `org-entry-properties' to
  14468. ;; retrieve it, but specify the wanted property.
  14469. (cdr (assoc-string property (org-entry-properties nil property))))
  14470. ((and inherit
  14471. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14472. (org-entry-get-with-inheritance property literal-nil))
  14473. (t
  14474. (let* ((local (org-property--local-values property literal-nil))
  14475. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14476. (if literal-nil value (org-not-nil value)))))))
  14477. (defun org-property-or-variable-value (var &optional inherit)
  14478. "Check if there is a property fixing the value of VAR.
  14479. If yes, return this value. If not, return the current value of the variable."
  14480. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14481. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14482. (read prop)
  14483. (symbol-value var))))
  14484. (defun org-entry-delete (pom property)
  14485. "Delete PROPERTY from entry at point-or-marker POM.
  14486. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14487. non-nil when a property was removed."
  14488. (unless (member property org-special-properties)
  14489. (org-with-point-at pom
  14490. (let ((range (org-get-property-block)))
  14491. (when range
  14492. (let* ((begin (car range))
  14493. (origin (cdr range))
  14494. (end (copy-marker origin))
  14495. (re (org-re-property
  14496. (concat (regexp-quote property) "\\+?") t t)))
  14497. (goto-char begin)
  14498. (while (re-search-forward re end t)
  14499. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14500. ;; If drawer is empty, remove it altogether.
  14501. (when (= begin end)
  14502. (delete-region (line-beginning-position 0)
  14503. (line-beginning-position 2)))
  14504. ;; Return non-nil if some property was removed.
  14505. (prog1 (/= end origin) (set-marker end nil))))))))
  14506. ;; Multi-values properties are properties that contain multiple values
  14507. ;; These values are assumed to be single words, separated by whitespace.
  14508. (defun org-entry-add-to-multivalued-property (pom property value)
  14509. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14510. (let* ((old (org-entry-get pom property))
  14511. (values (and old (org-split-string old "[ \t]"))))
  14512. (setq value (org-entry-protect-space value))
  14513. (unless (member value values)
  14514. (setq values (append values (list value)))
  14515. (org-entry-put pom property
  14516. (mapconcat 'identity values " ")))))
  14517. (defun org-entry-remove-from-multivalued-property (pom property value)
  14518. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14519. (let* ((old (org-entry-get pom property))
  14520. (values (and old (org-split-string old "[ \t]"))))
  14521. (setq value (org-entry-protect-space value))
  14522. (when (member value values)
  14523. (setq values (delete value values))
  14524. (org-entry-put pom property
  14525. (mapconcat 'identity values " ")))))
  14526. (defun org-entry-member-in-multivalued-property (pom property value)
  14527. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14528. (let* ((old (org-entry-get pom property))
  14529. (values (and old (org-split-string old "[ \t]"))))
  14530. (setq value (org-entry-protect-space value))
  14531. (member value values)))
  14532. (defun org-entry-get-multivalued-property (pom property)
  14533. "Return a list of values in a multivalued property."
  14534. (let* ((value (org-entry-get pom property))
  14535. (values (and value (org-split-string value "[ \t]"))))
  14536. (mapcar 'org-entry-restore-space values)))
  14537. (defun org-entry-put-multivalued-property (pom property &rest values)
  14538. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14539. VALUES should be a list of strings. Spaces will be protected."
  14540. (org-entry-put pom property
  14541. (mapconcat 'org-entry-protect-space values " "))
  14542. (let* ((value (org-entry-get pom property))
  14543. (values (and value (org-split-string value "[ \t]"))))
  14544. (mapcar 'org-entry-restore-space values)))
  14545. (defun org-entry-protect-space (s)
  14546. "Protect spaces and newline in string S."
  14547. (while (string-match " " s)
  14548. (setq s (replace-match "%20" t t s)))
  14549. (while (string-match "\n" s)
  14550. (setq s (replace-match "%0A" t t s)))
  14551. s)
  14552. (defun org-entry-restore-space (s)
  14553. "Restore spaces and newline in string S."
  14554. (while (string-match "%20" s)
  14555. (setq s (replace-match " " t t s)))
  14556. (while (string-match "%0A" s)
  14557. (setq s (replace-match "\n" t t s)))
  14558. s)
  14559. (defvar org-entry-property-inherited-from (make-marker)
  14560. "Marker pointing to the entry from where a property was inherited.
  14561. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14562. location of the entry where the inheritance search matched. If there was
  14563. no match, the marker will point nowhere.
  14564. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14565. is set.")
  14566. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14567. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14568. The search will stop at the first ancestor which has the property defined.
  14569. If the value found is \"nil\", return nil to show that the property
  14570. should be considered as undefined (this is the meaning of nil here).
  14571. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14572. (move-marker org-entry-property-inherited-from nil)
  14573. (org-with-wide-buffer
  14574. (let (value)
  14575. (catch 'exit
  14576. (while t
  14577. (let ((v (org-property--local-values property literal-nil)))
  14578. (when v
  14579. (setq value
  14580. (concat (mapconcat #'identity (delq nil v) " ")
  14581. (and value " ")
  14582. value)))
  14583. (cond
  14584. ((car v)
  14585. (org-back-to-heading t)
  14586. (move-marker org-entry-property-inherited-from (point))
  14587. (throw 'exit nil))
  14588. ((org-up-heading-safe))
  14589. (t
  14590. (let ((global
  14591. (cdr (or (assoc-string property org-file-properties t)
  14592. (assoc-string property org-global-properties t)
  14593. (assoc-string property org-global-properties-fixed t)))))
  14594. (cond ((not global))
  14595. (value (setq value (concat global " " value)))
  14596. (t (setq value global))))
  14597. (throw 'exit nil))))))
  14598. (if literal-nil value (org-not-nil value)))))
  14599. (defvar org-property-changed-functions nil
  14600. "Hook called when the value of a property has changed.
  14601. Each hook function should accept two arguments, the name of the property
  14602. and the new value.")
  14603. (defun org-entry-put (pom property value)
  14604. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14605. If the value is nil, it is converted to the empty string. If it
  14606. is not a string, an error is raised. Also raise an error on
  14607. invalid property names.
  14608. PROPERTY can be any regular property (see
  14609. `org-special-properties'). It can also be \"TODO\",
  14610. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14611. For the last two properties, VALUE may have any of the special
  14612. values \"earlier\" and \"later\". The function then increases or
  14613. decreases scheduled or deadline date by one day."
  14614. (cond ((null value) (setq value ""))
  14615. ((not (stringp value)) (error "Properties values should be strings"))
  14616. ((not (org--valid-property-p property))
  14617. (user-error "Invalid property name: \"%s\"" property)))
  14618. (org-with-point-at pom
  14619. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14620. (org-back-to-heading t)
  14621. (org-with-limited-levels (org-back-to-heading t)))
  14622. (let ((beg (point)))
  14623. (cond
  14624. ((equal property "TODO")
  14625. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14626. ((not (member value org-todo-keywords-1))
  14627. (user-error "\"%s\" is not a valid TODO state" value)))
  14628. (org-todo value)
  14629. (org-set-tags nil 'align))
  14630. ((equal property "PRIORITY")
  14631. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14632. (org-set-tags nil 'align))
  14633. ((equal property "SCHEDULED")
  14634. (forward-line)
  14635. (if (and (org-looking-at-p org-planning-line-re)
  14636. (re-search-forward
  14637. org-scheduled-time-regexp (line-end-position) t))
  14638. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14639. ((string= value "later") (org-timestamp-change 1 'day))
  14640. ((string= value "") (org-schedule '(4)))
  14641. (t (org-schedule nil value)))
  14642. (if (member value '("earlier" "later" ""))
  14643. (call-interactively #'org-schedule)
  14644. (org-schedule nil value))))
  14645. ((equal property "DEADLINE")
  14646. (forward-line)
  14647. (if (and (org-looking-at-p org-planning-line-re)
  14648. (re-search-forward
  14649. org-deadline-time-regexp (line-end-position) t))
  14650. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14651. ((string= value "later") (org-timestamp-change 1 'day))
  14652. ((string= value "") (org-deadline '(4)))
  14653. (t (org-deadline nil value)))
  14654. (if (member value '("earlier" "later" ""))
  14655. (call-interactively #'org-deadline)
  14656. (org-deadline nil value))))
  14657. ((member property org-special-properties)
  14658. (error "The %s property cannot be set with `org-entry-put'" property))
  14659. (t
  14660. (let* ((range (org-get-property-block beg 'force))
  14661. (end (cdr range))
  14662. (case-fold-search t))
  14663. (goto-char (car range))
  14664. (if (re-search-forward (org-re-property property nil t) end t)
  14665. (progn (delete-region (match-beginning 0) (match-end 0))
  14666. (goto-char (match-beginning 0)))
  14667. (goto-char end)
  14668. (insert "\n")
  14669. (backward-char))
  14670. (insert ":" property ":")
  14671. (when value (insert " " value))
  14672. (org-indent-line)))))
  14673. (run-hook-with-args 'org-property-changed-functions property value)))
  14674. (defun org-buffer-property-keys
  14675. (&optional specials defaults columns ignore-malformed)
  14676. "Get all property keys in the current buffer.
  14677. When SPECIALS is non-nil, also list the special properties that
  14678. reflect things like tags and TODO state.
  14679. When DEFAULTS is non-nil, also include properties that has
  14680. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14681. DESCRIPTION, LOCATION, and LOGGING and others.
  14682. When COLUMNS in non-nil, also include property names given in
  14683. COLUMN formats in the current buffer.
  14684. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14685. automatically performed, such drawers will be silently ignored."
  14686. (let ((case-fold-search t)
  14687. (props (append
  14688. (and specials org-special-properties)
  14689. (and defaults (cons org-effort-property org-default-properties))
  14690. nil)))
  14691. (org-with-wide-buffer
  14692. (goto-char (point-min))
  14693. (while (re-search-forward org-property-start-re nil t)
  14694. (let ((range (org-get-property-block)))
  14695. (catch 'skip
  14696. (unless range
  14697. (when (and (not ignore-malformed)
  14698. (not (org-before-first-heading-p))
  14699. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14700. (line-beginning-position))))
  14701. (org-get-property-block nil t))
  14702. (throw 'skip nil))
  14703. (goto-char (car range))
  14704. (let ((begin (car range))
  14705. (end (cdr range)))
  14706. ;; Make sure that found property block is not located
  14707. ;; before current point, as it would generate an infloop.
  14708. ;; It can happen, for example, in the following
  14709. ;; situation:
  14710. ;;
  14711. ;; * Headline
  14712. ;; :PROPERTIES:
  14713. ;; ...
  14714. ;; :END:
  14715. ;; *************** Inlinetask
  14716. ;; #+BEGIN_EXAMPLE
  14717. ;; :PROPERTIES:
  14718. ;; #+END_EXAMPLE
  14719. ;;
  14720. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14721. (while (< (point) end)
  14722. (let ((p (progn (looking-at org-property-re)
  14723. (org-match-string-no-properties 2))))
  14724. ;; Only add true property name, not extension symbol.
  14725. (push (if (not (org-string-match-p "\\+\\'" p)) p
  14726. (substring p 0 -1))
  14727. props))
  14728. (forward-line))))
  14729. (outline-next-heading)))
  14730. (when columns
  14731. (goto-char (point-min))
  14732. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14733. (let ((element (org-element-at-point)))
  14734. (when (memq (org-element-type element) '(keyword node-property))
  14735. (let ((value (org-element-property :value element))
  14736. (start 0))
  14737. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14738. (setq start (match-end 0))
  14739. (let ((p (org-match-string-no-properties 1 value)))
  14740. (unless (member-ignore-case p org-special-properties)
  14741. (push p props))))))))))
  14742. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14743. (defun org-property-values (key)
  14744. "List all non-nil values of property KEY in current buffer."
  14745. (org-with-wide-buffer
  14746. (goto-char (point-min))
  14747. (let ((case-fold-search t)
  14748. (re (org-re-property key))
  14749. values)
  14750. (while (re-search-forward re nil t)
  14751. (push (org-entry-get (point) key) values))
  14752. (delete-dups values))))
  14753. (defun org-insert-property-drawer ()
  14754. "Insert a property drawer into the current entry."
  14755. (org-with-wide-buffer
  14756. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14757. (org-back-to-heading t)
  14758. (org-with-limited-levels (org-back-to-heading t)))
  14759. (forward-line)
  14760. (when (org-looking-at-p org-planning-line-re) (forward-line))
  14761. (unless (org-looking-at-p org-property-drawer-re)
  14762. ;; Make sure we start editing a line from current entry, not from
  14763. ;; next one. It prevents extending text properties or overlays
  14764. ;; belonging to the latter.
  14765. (when (bolp) (backward-char))
  14766. (let ((begin (1+ (point)))
  14767. (inhibit-read-only t))
  14768. (insert "\n:PROPERTIES:\n:END:")
  14769. (when (eobp) (insert "\n"))
  14770. (org-indent-region begin (point))))))
  14771. (defun org-insert-drawer (&optional arg drawer)
  14772. "Insert a drawer at point.
  14773. When optional argument ARG is non-nil, insert a property drawer.
  14774. Optional argument DRAWER, when non-nil, is a string representing
  14775. drawer's name. Otherwise, the user is prompted for a name.
  14776. If a region is active, insert the drawer around that region
  14777. instead.
  14778. Point is left between drawer's boundaries."
  14779. (interactive "P")
  14780. (let* ((drawer (if arg "PROPERTIES"
  14781. (or drawer (read-from-minibuffer "Drawer: ")))))
  14782. (cond
  14783. ;; With C-u, fall back on `org-insert-property-drawer'
  14784. (arg (org-insert-property-drawer))
  14785. ;; Check validity of suggested drawer's name.
  14786. ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14787. (user-error "Invalid drawer name"))
  14788. ;; With an active region, insert a drawer at point.
  14789. ((not (org-region-active-p))
  14790. (progn
  14791. (unless (bolp) (insert "\n"))
  14792. (insert (format ":%s:\n\n:END:\n" drawer))
  14793. (forward-line -2)))
  14794. ;; Otherwise, insert the drawer at point
  14795. (t
  14796. (let ((rbeg (region-beginning))
  14797. (rend (copy-marker (region-end))))
  14798. (unwind-protect
  14799. (progn
  14800. (goto-char rbeg)
  14801. (beginning-of-line)
  14802. (when (save-excursion
  14803. (re-search-forward org-outline-regexp-bol rend t))
  14804. (user-error "Drawers cannot contain headlines"))
  14805. ;; Position point at the beginning of the first
  14806. ;; non-blank line in region. Insert drawer's opening
  14807. ;; there, then indent it.
  14808. (org-skip-whitespace)
  14809. (beginning-of-line)
  14810. (insert ":" drawer ":\n")
  14811. (forward-line -1)
  14812. (indent-for-tab-command)
  14813. ;; Move point to the beginning of the first blank line
  14814. ;; after the last non-blank line in region. Insert
  14815. ;; drawer's closing, then indent it.
  14816. (goto-char rend)
  14817. (skip-chars-backward " \r\t\n")
  14818. (insert "\n:END:")
  14819. (deactivate-mark t)
  14820. (indent-for-tab-command)
  14821. (unless (eolp) (insert "\n")))
  14822. ;; Clear marker, whatever the outcome of insertion is.
  14823. (set-marker rend nil)))))))
  14824. (defvar org-property-set-functions-alist nil
  14825. "Property set function alist.
  14826. Each entry should have the following format:
  14827. (PROPERTY . READ-FUNCTION)
  14828. The read function will be called with the same argument as
  14829. `org-completing-read'.")
  14830. (defun org-set-property-function (property)
  14831. "Get the function that should be used to set PROPERTY.
  14832. This is computed according to `org-property-set-functions-alist'."
  14833. (or (cdr (assoc property org-property-set-functions-alist))
  14834. 'org-completing-read))
  14835. (defun org-read-property-value (property)
  14836. "Read PROPERTY value from user."
  14837. (let* ((completion-ignore-case t)
  14838. (allowed (org-property-get-allowed-values nil property 'table))
  14839. (cur (org-entry-get nil property))
  14840. (prompt (concat property " value"
  14841. (if (and cur (string-match "\\S-" cur))
  14842. (concat " [" cur "]") "") ": "))
  14843. (set-function (org-set-property-function property))
  14844. (val (if allowed
  14845. (funcall set-function prompt allowed nil
  14846. (not (get-text-property 0 'org-unrestricted
  14847. (caar allowed))))
  14848. (let (org-completion-use-ido org-completion-use-iswitchb)
  14849. (funcall set-function prompt
  14850. (mapcar 'list (org-property-values property))
  14851. nil nil "" nil cur)))))
  14852. (org-trim val)))
  14853. (defvar org-last-set-property nil)
  14854. (defvar org-last-set-property-value nil)
  14855. (defun org-read-property-name ()
  14856. "Read a property name."
  14857. (let ((completion-ignore-case t)
  14858. (default-prop (or (and (org-at-property-p)
  14859. (org-match-string-no-properties 2))
  14860. org-last-set-property)))
  14861. (org-completing-read
  14862. (concat "Property"
  14863. (if default-prop (concat " [" default-prop "]") "")
  14864. ": ")
  14865. (mapcar #'list (org-buffer-property-keys nil t t))
  14866. nil nil nil nil default-prop)))
  14867. (defun org-set-property-and-value (use-last)
  14868. "Allow to set [PROPERTY]: [value] direction from prompt.
  14869. When use-default, don't even ask, just use the last
  14870. \"[PROPERTY]: [value]\" string from the history."
  14871. (interactive "P")
  14872. (let* ((completion-ignore-case t)
  14873. (pv (or (and use-last org-last-set-property-value)
  14874. (org-completing-read
  14875. "Enter a \"[Property]: [value]\" pair: "
  14876. nil nil nil nil nil
  14877. org-last-set-property-value)))
  14878. prop val)
  14879. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14880. (setq prop (match-string 1 pv)
  14881. val (match-string 2 pv))
  14882. (org-set-property prop val))))
  14883. (defun org-set-property (property value)
  14884. "In the current entry, set PROPERTY to VALUE.
  14885. When called interactively, this will prompt for a property name, offering
  14886. completion on existing and default properties. And then it will prompt
  14887. for a value, offering completion either on allowed values (via an inherited
  14888. xxx_ALL property) or on existing values in other instances of this property
  14889. in the current file.
  14890. Throw an error when trying to set a property with an invalid name."
  14891. (interactive (list nil nil))
  14892. (let ((property (or property (org-read-property-name))))
  14893. ;; `org-entry-put' also makes the following check, but this one
  14894. ;; avoids polluting `org-last-set-property' and
  14895. ;; `org-last-set-property-value' needlessly.
  14896. (unless (org--valid-property-p property)
  14897. (user-error "Invalid property name: \"%s\"" property))
  14898. (let ((value (or value (org-read-property-value property)))
  14899. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14900. (setq org-last-set-property property)
  14901. (setq org-last-set-property-value (concat property ": " value))
  14902. ;; Possibly postprocess the inserted value:
  14903. (when fn (setq value (funcall fn value)))
  14904. (unless (equal (org-entry-get nil property) value)
  14905. (org-entry-put nil property value)))))
  14906. (defun org-find-property (property &optional value)
  14907. "Find first entry in buffer that sets PROPERTY.
  14908. When optional argument VALUE is non-nil, only consider an entry
  14909. if it contains PROPERTY set to this value. If PROPERTY should be
  14910. explicitly set to nil, use string \"nil\" for VALUE.
  14911. Return position where the entry begins, or nil if there is no
  14912. such entry. If narrowing is in effect, only search the visible
  14913. part of the buffer."
  14914. (save-excursion
  14915. (goto-char (point-min))
  14916. (let ((case-fold-search t)
  14917. (re (org-re-property property nil (not value) value)))
  14918. (catch 'exit
  14919. (while (re-search-forward re nil t)
  14920. (when (if value (org-at-property-p)
  14921. (org-entry-get (point) property nil t))
  14922. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14923. (defun org-delete-property (property)
  14924. "In the current entry, delete PROPERTY."
  14925. (interactive
  14926. (let* ((completion-ignore-case t)
  14927. (cat (org-entry-get (point) "CATEGORY"))
  14928. (props0 (org-entry-properties nil 'standard))
  14929. (props (if cat props0
  14930. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14931. (prop (if (< 1 (length props))
  14932. (completing-read "Property: " props nil t)
  14933. (caar props))))
  14934. (list prop)))
  14935. (if (not property)
  14936. (message "No property to delete in this entry")
  14937. (org-entry-delete nil property)
  14938. (message "Property \"%s\" deleted" property)))
  14939. (defun org-delete-property-globally (property)
  14940. "Remove PROPERTY globally, from all entries.
  14941. This function ignores narrowing, if any."
  14942. (interactive
  14943. (let* ((completion-ignore-case t)
  14944. (prop (completing-read
  14945. "Globally remove property: "
  14946. (mapcar #'list (org-buffer-property-keys)))))
  14947. (list prop)))
  14948. (org-with-wide-buffer
  14949. (goto-char (point-min))
  14950. (let ((count 0)
  14951. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14952. (while (re-search-forward re nil t)
  14953. (when (org-entry-delete (point) property) (incf count)))
  14954. (message "Property \"%s\" removed from %d entries" property count))))
  14955. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14956. (defun org-compute-property-at-point ()
  14957. "Compute the property at point.
  14958. This looks for an enclosing column format, extracts the operator and
  14959. then applies it to the property in the column format's scope."
  14960. (interactive)
  14961. (unless (org-at-property-p)
  14962. (user-error "Not at a property"))
  14963. (let ((prop (org-match-string-no-properties 2)))
  14964. (org-columns-get-format-and-top-level)
  14965. (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
  14966. (user-error "No operator defined for property %s" prop))
  14967. (org-columns-compute prop)))
  14968. (defvar org-property-allowed-value-functions nil
  14969. "Hook for functions supplying allowed values for a specific property.
  14970. The functions must take a single argument, the name of the property, and
  14971. return a flat list of allowed values. If \":ETC\" is one of
  14972. the values, this means that these values are intended as defaults for
  14973. completion, but that other values should be allowed too.
  14974. The functions must return nil if they are not responsible for this
  14975. property.")
  14976. (defun org-property-get-allowed-values (pom property &optional table)
  14977. "Get allowed values for the property PROPERTY.
  14978. When TABLE is non-nil, return an alist that can directly be used for
  14979. completion."
  14980. (let (vals)
  14981. (cond
  14982. ((equal property "TODO")
  14983. (setq vals (org-with-point-at pom
  14984. (append org-todo-keywords-1 '("")))))
  14985. ((equal property "PRIORITY")
  14986. (let ((n org-lowest-priority))
  14987. (while (>= n org-highest-priority)
  14988. (push (char-to-string n) vals)
  14989. (setq n (1- n)))))
  14990. ((equal property "CATEGORY"))
  14991. ((member property org-special-properties))
  14992. ((setq vals (run-hook-with-args-until-success
  14993. 'org-property-allowed-value-functions property)))
  14994. (t
  14995. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14996. (when (and vals (string-match "\\S-" vals))
  14997. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14998. (setq vals (mapcar (lambda (x)
  14999. (cond ((stringp x) x)
  15000. ((numberp x) (number-to-string x))
  15001. ((symbolp x) (symbol-name x))
  15002. (t "???")))
  15003. vals)))))
  15004. (when (member ":ETC" vals)
  15005. (setq vals (remove ":ETC" vals))
  15006. (org-add-props (car vals) '(org-unrestricted t)))
  15007. (if table (mapcar 'list vals) vals)))
  15008. (defun org-property-previous-allowed-value (&optional _previous)
  15009. "Switch to the next allowed value for this property."
  15010. (interactive)
  15011. (org-property-next-allowed-value t))
  15012. (defun org-property-next-allowed-value (&optional previous)
  15013. "Switch to the next allowed value for this property."
  15014. (interactive)
  15015. (unless (org-at-property-p)
  15016. (user-error "Not at a property"))
  15017. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15018. (key (match-string 2))
  15019. (value (match-string 3))
  15020. (allowed (or (org-property-get-allowed-values (point) key)
  15021. (and (member value '("[ ]" "[-]" "[X]"))
  15022. '("[ ]" "[X]"))))
  15023. (heading (save-match-data (nth 4 (org-heading-components))))
  15024. nval)
  15025. (unless allowed
  15026. (user-error "Allowed values for this property have not been defined"))
  15027. (when previous (setq allowed (reverse allowed)))
  15028. (when (member value allowed)
  15029. (setq nval (car (cdr (member value allowed)))))
  15030. (setq nval (or nval (car allowed)))
  15031. (when (equal nval value)
  15032. (user-error "Only one allowed value for this property"))
  15033. (org-at-property-p)
  15034. (replace-match (concat " :" key ": " nval) t t)
  15035. (org-indent-line)
  15036. (beginning-of-line 1)
  15037. (skip-chars-forward " \t")
  15038. (when (equal prop org-effort-property)
  15039. (org-refresh-property
  15040. '((effort . identity)
  15041. (effort-minutes . org-duration-string-to-minutes))
  15042. nval)
  15043. (when (string= org-clock-current-task heading)
  15044. (setq org-clock-effort nval)
  15045. (org-clock-update-mode-line)))
  15046. (run-hook-with-args 'org-property-changed-functions key nval)))
  15047. (defun org-find-olp (path &optional this-buffer)
  15048. "Return a marker pointing to the entry at outline path OLP.
  15049. If anything goes wrong, throw an error.
  15050. You can wrap this call to catch the error like this:
  15051. \(condition-case msg
  15052. \(org-mobile-locate-entry (match-string 4))
  15053. \(error (nth 1 msg)))
  15054. The return value will then be either a string with the error message,
  15055. or a marker if everything is OK.
  15056. If THIS-BUFFER is set, the outline path does not contain a file,
  15057. only headings."
  15058. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15059. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15060. (level 1)
  15061. (lmin 1)
  15062. (lmax 1)
  15063. end found flevel)
  15064. (unless buffer (error "File not found :%s" file))
  15065. (with-current-buffer buffer
  15066. (org-with-wide-buffer
  15067. (goto-char (point-min))
  15068. (dolist (heading path)
  15069. (let ((re (format org-complex-heading-regexp-format
  15070. (regexp-quote heading)))
  15071. (cnt 0))
  15072. (while (re-search-forward re end t)
  15073. (setq level (- (match-end 1) (match-beginning 1)))
  15074. (when (and (>= level lmin) (<= level lmax))
  15075. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15076. (when (= cnt 0)
  15077. (error "Heading not found on level %d: %s" lmax heading))
  15078. (when (> cnt 1)
  15079. (error "Heading not unique on level %d: %s" lmax heading))
  15080. (goto-char found)
  15081. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15082. (setq end (save-excursion (org-end-of-subtree t t)))))
  15083. (when (org-at-heading-p)
  15084. (point-marker))))))
  15085. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15086. "Find node HEADING in BUFFER.
  15087. Return a marker to the heading if it was found, or nil if not.
  15088. If POS-ONLY is set, return just the position instead of a marker.
  15089. The heading text must match exact, but it may have a TODO keyword,
  15090. a priority cookie and tags in the standard locations."
  15091. (with-current-buffer (or buffer (current-buffer))
  15092. (save-excursion
  15093. (save-restriction
  15094. (widen)
  15095. (goto-char (point-min))
  15096. (let (case-fold-search)
  15097. (when (re-search-forward
  15098. (format org-complex-heading-regexp-format
  15099. (regexp-quote heading)) nil t)
  15100. (if pos-only
  15101. (match-beginning 0)
  15102. (move-marker (make-marker) (match-beginning 0)))))))))
  15103. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15104. "Find Org node headline HEADING in all .org files in directory DIR.
  15105. When the target headline is found, return a marker to this location."
  15106. (let ((files (directory-files (or dir default-directory)
  15107. t "\\`[^.#].*\\.org\\'"))
  15108. visiting m buffer)
  15109. (catch 'found
  15110. (dolist (file files)
  15111. (message "trying %s" file)
  15112. (setq visiting (org-find-base-buffer-visiting file))
  15113. (setq buffer (or visiting (find-file-noselect file)))
  15114. (setq m (org-find-exact-headline-in-buffer
  15115. heading buffer))
  15116. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15117. (and m (throw 'found m))))))
  15118. (defun org-find-entry-with-id (ident)
  15119. "Locate the entry that contains the ID property with exact value IDENT.
  15120. IDENT can be a string, a symbol or a number, this function will search for
  15121. the string representation of it.
  15122. Return the position where this entry starts, or nil if there is no such entry."
  15123. (interactive "sID: ")
  15124. (let ((id (cond
  15125. ((stringp ident) ident)
  15126. ((symbolp ident) (symbol-name ident))
  15127. ((numberp ident) (number-to-string ident))
  15128. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15129. (org-with-wide-buffer (org-find-property "ID" id))))
  15130. ;;;; Timestamps
  15131. (defvar org-last-changed-timestamp nil)
  15132. (defvar org-last-inserted-timestamp nil
  15133. "The last time stamp inserted with `org-insert-time-stamp'.")
  15134. (defvar org-ts-what) ; dynamically scoped parameter
  15135. (defun org-time-stamp (arg &optional inactive)
  15136. "Prompt for a date/time and insert a time stamp.
  15137. If the user specifies a time like HH:MM or if this command is
  15138. called with at least one prefix argument, the time stamp contains
  15139. the date and the time. Otherwise, only the date is included.
  15140. All parts of a date not specified by the user are filled in from
  15141. the timestamp at point, if any, or the current date/time
  15142. otherwise.
  15143. If there is already a timestamp at the cursor, it is replaced.
  15144. With two universal prefix arguments, insert an active timestamp
  15145. with the current time without prompting the user.
  15146. When called from lisp, the timestamp is inactive if INACTIVE is
  15147. non-nil."
  15148. (interactive "P")
  15149. (let* ((ts (cond
  15150. ((org-at-date-range-p t)
  15151. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15152. ((org-at-timestamp-p t) (match-string 0))))
  15153. ;; Default time is either the timestamp at point or today.
  15154. ;; When entering a range, only the range start is considered.
  15155. (default-time (if (not ts) (current-time)
  15156. (apply #'encode-time (org-parse-time-string ts))))
  15157. (default-input (and ts (org-get-compact-tod ts)))
  15158. (repeater (and ts
  15159. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15160. (match-string 0 ts)))
  15161. org-time-was-given
  15162. org-end-time-was-given
  15163. (time
  15164. (and (if (equal arg '(16)) (current-time)
  15165. ;; Preserve `this-command' and `last-command'.
  15166. (let ((this-command this-command)
  15167. (last-command last-command))
  15168. (org-read-date
  15169. arg 'totime nil nil default-time default-input
  15170. inactive))))))
  15171. (cond
  15172. ((and ts
  15173. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15174. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15175. (insert "--")
  15176. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15177. (ts
  15178. ;; Make sure we're on a timestamp. When in the middle of a date
  15179. ;; range, move arbitrarily to range end.
  15180. (unless (org-at-timestamp-p t)
  15181. (skip-chars-forward "-")
  15182. (org-at-timestamp-p t))
  15183. (replace-match "")
  15184. (setq org-last-changed-timestamp
  15185. (org-insert-time-stamp
  15186. time (or org-time-was-given arg)
  15187. inactive nil nil (list org-end-time-was-given)))
  15188. (when repeater
  15189. (backward-char)
  15190. (insert " " repeater)
  15191. (setq org-last-changed-timestamp
  15192. (concat (substring org-last-inserted-timestamp 0 -1)
  15193. " " repeater ">")))
  15194. (message "Timestamp updated"))
  15195. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15196. (t (org-insert-time-stamp
  15197. time (or org-time-was-given arg) inactive nil nil
  15198. (list org-end-time-was-given))))))
  15199. ;; FIXME: can we use this for something else, like computing time differences?
  15200. (defun org-get-compact-tod (s)
  15201. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15202. (let* ((t1 (match-string 1 s))
  15203. (h1 (string-to-number (match-string 2 s)))
  15204. (m1 (string-to-number (match-string 3 s)))
  15205. (t2 (and (match-end 4) (match-string 5 s)))
  15206. (h2 (and t2 (string-to-number (match-string 6 s))))
  15207. (m2 (and t2 (string-to-number (match-string 7 s))))
  15208. dh dm)
  15209. (if (not t2)
  15210. t1
  15211. (setq dh (- h2 h1) dm (- m2 m1))
  15212. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15213. (concat t1 "+" (number-to-string dh)
  15214. (and (/= 0 dm) (format ":%02d" dm)))))))
  15215. (defun org-time-stamp-inactive (&optional arg)
  15216. "Insert an inactive time stamp.
  15217. An inactive time stamp is enclosed in square brackets instead of angle
  15218. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15219. does not link to the calendar and cannot be changed with the S-cursor keys.
  15220. So these are more for recording a certain time/date."
  15221. (interactive "P")
  15222. (org-time-stamp arg 'inactive))
  15223. (defvar org-date-ovl (make-overlay 1 1))
  15224. (overlay-put org-date-ovl 'face 'org-date-selected)
  15225. (org-detach-overlay org-date-ovl)
  15226. (defvar org-ans1) ; dynamically scoped parameter
  15227. (defvar org-ans2) ; dynamically scoped parameter
  15228. (defvar org-plain-time-of-day-regexp) ; defined below
  15229. (defvar org-overriding-default-time nil) ; dynamically scoped
  15230. (defvar org-read-date-overlay nil)
  15231. (defvar org-dcst nil) ; dynamically scoped
  15232. (defvar org-read-date-history nil)
  15233. (defvar org-read-date-final-answer nil)
  15234. (defvar org-read-date-analyze-futurep nil)
  15235. (defvar org-read-date-analyze-forced-year nil)
  15236. (defvar org-read-date-inactive)
  15237. (defvar org-read-date-minibuffer-local-map
  15238. (let* ((map (make-sparse-keymap)))
  15239. (set-keymap-parent map minibuffer-local-map)
  15240. (org-defkey map (kbd ".")
  15241. (lambda () (interactive)
  15242. ;; Are we at the beginning of the prompt?
  15243. (if (org-looking-back "^[^:]+: "
  15244. (let ((inhibit-field-text-motion t))
  15245. (line-beginning-position)))
  15246. (org-eval-in-calendar '(calendar-goto-today))
  15247. (insert "."))))
  15248. (org-defkey map (kbd "C-.")
  15249. (lambda () (interactive)
  15250. (org-eval-in-calendar '(calendar-goto-today))))
  15251. (org-defkey map [(meta shift left)]
  15252. (lambda () (interactive)
  15253. (org-eval-in-calendar '(calendar-backward-month 1))))
  15254. (org-defkey map [(meta shift right)]
  15255. (lambda () (interactive)
  15256. (org-eval-in-calendar '(calendar-forward-month 1))))
  15257. (org-defkey map [(meta shift up)]
  15258. (lambda () (interactive)
  15259. (org-eval-in-calendar '(calendar-backward-year 1))))
  15260. (org-defkey map [(meta shift down)]
  15261. (lambda () (interactive)
  15262. (org-eval-in-calendar '(calendar-forward-year 1))))
  15263. (org-defkey map [?\e (shift left)]
  15264. (lambda () (interactive)
  15265. (org-eval-in-calendar '(calendar-backward-month 1))))
  15266. (org-defkey map [?\e (shift right)]
  15267. (lambda () (interactive)
  15268. (org-eval-in-calendar '(calendar-forward-month 1))))
  15269. (org-defkey map [?\e (shift up)]
  15270. (lambda () (interactive)
  15271. (org-eval-in-calendar '(calendar-backward-year 1))))
  15272. (org-defkey map [?\e (shift down)]
  15273. (lambda () (interactive)
  15274. (org-eval-in-calendar '(calendar-forward-year 1))))
  15275. (org-defkey map [(shift up)]
  15276. (lambda () (interactive)
  15277. (org-eval-in-calendar '(calendar-backward-week 1))))
  15278. (org-defkey map [(shift down)]
  15279. (lambda () (interactive)
  15280. (org-eval-in-calendar '(calendar-forward-week 1))))
  15281. (org-defkey map [(shift left)]
  15282. (lambda () (interactive)
  15283. (org-eval-in-calendar '(calendar-backward-day 1))))
  15284. (org-defkey map [(shift right)]
  15285. (lambda () (interactive)
  15286. (org-eval-in-calendar '(calendar-forward-day 1))))
  15287. (org-defkey map "!"
  15288. (lambda () (interactive)
  15289. (org-eval-in-calendar '(diary-view-entries))
  15290. (message "")))
  15291. (org-defkey map ">"
  15292. (lambda () (interactive)
  15293. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15294. (org-defkey map "<"
  15295. (lambda () (interactive)
  15296. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15297. (org-defkey map "\C-v"
  15298. (lambda () (interactive)
  15299. (org-eval-in-calendar
  15300. '(calendar-scroll-left-three-months 1))))
  15301. (org-defkey map "\M-v"
  15302. (lambda () (interactive)
  15303. (org-eval-in-calendar
  15304. '(calendar-scroll-right-three-months 1))))
  15305. map)
  15306. "Keymap for minibuffer commands when using `org-read-date'.")
  15307. (defvar org-def)
  15308. (defvar org-defdecode)
  15309. (defvar org-with-time)
  15310. (defvar calendar-setup) ; Dynamically scoped.
  15311. (defun org-read-date (&optional with-time to-time from-string prompt
  15312. default-time default-input inactive)
  15313. "Read a date, possibly a time, and make things smooth for the user.
  15314. The prompt will suggest to enter an ISO date, but you can also enter anything
  15315. which will at least partially be understood by `parse-time-string'.
  15316. Unrecognized parts of the date will default to the current day, month, year,
  15317. hour and minute. If this command is called to replace a timestamp at point,
  15318. or to enter the second timestamp of a range, the default time is taken
  15319. from the existing stamp. Furthermore, the command prefers the future,
  15320. so if you are giving a date where the year is not given, and the day-month
  15321. combination is already past in the current year, it will assume you
  15322. mean next year. For details, see the manual. A few examples:
  15323. 3-2-5 --> 2003-02-05
  15324. feb 15 --> currentyear-02-15
  15325. 2/15 --> currentyear-02-15
  15326. sep 12 9 --> 2009-09-12
  15327. 12:45 --> today 12:45
  15328. 22 sept 0:34 --> currentyear-09-22 0:34
  15329. 12 --> currentyear-currentmonth-12
  15330. Fri --> nearest Friday after today
  15331. -Tue --> last Tuesday
  15332. etc.
  15333. Furthermore you can specify a relative date by giving, as the *first* thing
  15334. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15335. change in days weeks, months, years.
  15336. With a single plus or minus, the date is relative to today. With a double
  15337. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15338. +4d --> four days from today
  15339. +4 --> same as above
  15340. +2w --> two weeks from today
  15341. ++5 --> five days from default date
  15342. The function understands only English month and weekday abbreviations.
  15343. While prompting, a calendar is popped up - you can also select the
  15344. date with the mouse (button 1). The calendar shows a period of three
  15345. months. To scroll it to other months, use the keys `>' and `<'.
  15346. If you don't like the calendar, turn it off with
  15347. (setq org-read-date-popup-calendar nil)
  15348. With optional argument TO-TIME, the date will immediately be converted
  15349. to an internal time.
  15350. With an optional argument WITH-TIME, the prompt will suggest to
  15351. also insert a time. Note that when WITH-TIME is not set, you can
  15352. still enter a time, and this function will inform the calling routine
  15353. about this change. The calling routine may then choose to change the
  15354. format used to insert the time stamp into the buffer to include the time.
  15355. With optional argument FROM-STRING, read from this string instead from
  15356. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15357. the time/date that is used for everything that is not specified by the
  15358. user."
  15359. (require 'parse-time)
  15360. (let* ((org-with-time with-time)
  15361. (org-time-stamp-rounding-minutes
  15362. (if (equal org-with-time '(16))
  15363. '(0 0)
  15364. org-time-stamp-rounding-minutes))
  15365. (org-dcst org-display-custom-times)
  15366. (ct (org-current-time))
  15367. (org-def (or org-overriding-default-time default-time ct))
  15368. (org-defdecode (decode-time org-def))
  15369. (cur-frame (selected-frame))
  15370. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15371. (calendar-setup
  15372. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15373. (calendar-move-hook nil)
  15374. (calendar-view-diary-initially-flag nil)
  15375. (calendar-view-holidays-initially-flag nil)
  15376. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15377. ;; Rationalize `org-def' and `org-defdecode', if required.
  15378. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15379. (setf (nth 2 org-defdecode) -1)
  15380. (setf (nth 1 org-defdecode) 59)
  15381. (setq org-def (apply #'encode-time org-defdecode))
  15382. (setq org-defdecode (decode-time org-def)))
  15383. (let* ((timestr (format-time-string
  15384. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15385. org-def))
  15386. (prompt (concat (if prompt (concat prompt " ") "")
  15387. (format "Date+time [%s]: " timestr))))
  15388. (cond
  15389. (from-string (setq ans from-string))
  15390. (org-read-date-popup-calendar
  15391. (save-excursion
  15392. (save-window-excursion
  15393. (calendar)
  15394. (when (eq calendar-setup 'calendar-only)
  15395. (setq cal-frame
  15396. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15397. (select-frame cal-frame))
  15398. (org-eval-in-calendar '(setq cursor-type nil) t)
  15399. (unwind-protect
  15400. (progn
  15401. (calendar-forward-day (- (time-to-days org-def)
  15402. (calendar-absolute-from-gregorian
  15403. (calendar-current-date))))
  15404. (org-eval-in-calendar nil t)
  15405. (let* ((old-map (current-local-map))
  15406. (map (copy-keymap calendar-mode-map))
  15407. (minibuffer-local-map
  15408. (copy-keymap org-read-date-minibuffer-local-map)))
  15409. (org-defkey map (kbd "RET") 'org-calendar-select)
  15410. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15411. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15412. (unwind-protect
  15413. (progn
  15414. (use-local-map map)
  15415. (setq org-read-date-inactive inactive)
  15416. (add-hook 'post-command-hook 'org-read-date-display)
  15417. (setq org-ans0
  15418. (read-string prompt
  15419. default-input
  15420. 'org-read-date-history
  15421. nil))
  15422. ;; org-ans0: from prompt
  15423. ;; org-ans1: from mouse click
  15424. ;; org-ans2: from calendar motion
  15425. (setq ans
  15426. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15427. (remove-hook 'post-command-hook 'org-read-date-display)
  15428. (use-local-map old-map)
  15429. (when org-read-date-overlay
  15430. (delete-overlay org-read-date-overlay)
  15431. (setq org-read-date-overlay nil)))))
  15432. (bury-buffer "*Calendar*")
  15433. (when cal-frame
  15434. (delete-frame cal-frame)
  15435. (select-frame-set-input-focus cur-frame))))))
  15436. (t ; Naked prompt only
  15437. (unwind-protect
  15438. (setq ans (read-string prompt default-input
  15439. 'org-read-date-history timestr))
  15440. (when org-read-date-overlay
  15441. (delete-overlay org-read-date-overlay)
  15442. (setq org-read-date-overlay nil))))))
  15443. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15444. (when org-read-date-analyze-forced-year
  15445. (message "Year was forced into %s"
  15446. (if org-read-date-force-compatible-dates
  15447. "compatible range (1970-2037)"
  15448. "range representable on this machine"))
  15449. (ding))
  15450. ;; One round trip to get rid of 34th of August and stuff like that....
  15451. (setq final (decode-time (apply 'encode-time final)))
  15452. (setq org-read-date-final-answer ans)
  15453. (if to-time
  15454. (apply 'encode-time final)
  15455. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15456. (format "%04d-%02d-%02d %02d:%02d"
  15457. (nth 5 final) (nth 4 final) (nth 3 final)
  15458. (nth 2 final) (nth 1 final))
  15459. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15460. (defun org-read-date-display ()
  15461. "Display the current date prompt interpretation in the minibuffer."
  15462. (when org-read-date-display-live
  15463. (when org-read-date-overlay
  15464. (delete-overlay org-read-date-overlay))
  15465. (when (minibufferp (current-buffer))
  15466. (save-excursion
  15467. (end-of-line 1)
  15468. (while (not (equal (buffer-substring
  15469. (max (point-min) (- (point) 4)) (point))
  15470. " "))
  15471. (insert " ")))
  15472. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15473. " " (or org-ans1 org-ans2)))
  15474. (org-end-time-was-given nil)
  15475. (f (org-read-date-analyze ans org-def org-defdecode))
  15476. (fmts (if org-dcst
  15477. org-time-stamp-custom-formats
  15478. org-time-stamp-formats))
  15479. (fmt (if (or org-with-time
  15480. (and (boundp 'org-time-was-given) org-time-was-given))
  15481. (cdr fmts)
  15482. (car fmts)))
  15483. (txt (format-time-string fmt (apply 'encode-time f)))
  15484. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15485. (txt (concat "=> " txt)))
  15486. (when (and org-end-time-was-given
  15487. (string-match org-plain-time-of-day-regexp txt))
  15488. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15489. org-end-time-was-given
  15490. (substring txt (match-end 0)))))
  15491. (when org-read-date-analyze-futurep
  15492. (setq txt (concat txt " (=>F)")))
  15493. (setq org-read-date-overlay
  15494. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15495. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15496. (defun org-read-date-analyze (ans def defdecode)
  15497. "Analyze the combined answer of the date prompt."
  15498. ;; FIXME: cleanup and comment
  15499. ;; Pass `current-time' result to `decode-time' (instead of calling
  15500. ;; without arguments) so that only `current-time' has to be
  15501. ;; overriden in tests.
  15502. (let ((org-def def)
  15503. (org-defdecode defdecode)
  15504. (nowdecode (decode-time (current-time)))
  15505. delta deltan deltaw deltadef year month day
  15506. hour minute second wday pm h2 m2 tl wday1
  15507. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15508. (setq org-read-date-analyze-futurep nil
  15509. org-read-date-analyze-forced-year nil)
  15510. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15511. (setq ans "+0"))
  15512. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15513. (setq ans (replace-match "" t t ans)
  15514. deltan (car delta)
  15515. deltaw (nth 1 delta)
  15516. deltadef (nth 2 delta)))
  15517. ;; Check if there is an iso week date in there. If yes, store the
  15518. ;; info and postpone interpreting it until the rest of the parsing
  15519. ;; is done.
  15520. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15521. (setq iso-year (when (match-end 1)
  15522. (org-small-year-to-year
  15523. (string-to-number (match-string 1 ans))))
  15524. iso-weekday (when (match-end 3)
  15525. (string-to-number (match-string 3 ans)))
  15526. iso-week (string-to-number (match-string 2 ans)))
  15527. (setq ans (replace-match "" t t ans)))
  15528. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15529. (when (string-match
  15530. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15531. (setq year (if (match-end 2)
  15532. (string-to-number (match-string 2 ans))
  15533. (progn (setq kill-year t)
  15534. (string-to-number (format-time-string "%Y"))))
  15535. month (string-to-number (match-string 3 ans))
  15536. day (string-to-number (match-string 4 ans)))
  15537. (when (< year 100) (setq year (+ 2000 year)))
  15538. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15539. t nil ans)))
  15540. ;; Help matching dotted european dates
  15541. (when (string-match
  15542. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15543. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15544. (setq kill-year t)
  15545. (string-to-number (format-time-string "%Y")))
  15546. day (string-to-number (match-string 1 ans))
  15547. month (string-to-number (match-string 2 ans))
  15548. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15549. t nil ans)))
  15550. ;; Help matching american dates, like 5/30 or 5/30/7
  15551. (when (string-match
  15552. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15553. (setq year (if (match-end 4)
  15554. (string-to-number (match-string 4 ans))
  15555. (progn (setq kill-year t)
  15556. (string-to-number (format-time-string "%Y"))))
  15557. month (string-to-number (match-string 1 ans))
  15558. day (string-to-number (match-string 2 ans)))
  15559. (when (< year 100) (setq year (+ 2000 year)))
  15560. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15561. t nil ans)))
  15562. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15563. ;; If there is a time with am/pm, and *no* time without it, we convert
  15564. ;; so that matching will be successful.
  15565. (loop for i from 1 to 2 do ; twice, for end time as well
  15566. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15567. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15568. (setq hour (string-to-number (match-string 1 ans))
  15569. minute (if (match-end 3)
  15570. (string-to-number (match-string 3 ans))
  15571. 0)
  15572. pm (equal ?p
  15573. (string-to-char (downcase (match-string 4 ans)))))
  15574. (if (and (= hour 12) (not pm))
  15575. (setq hour 0)
  15576. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15577. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15578. t t ans))))
  15579. ;; Check if a time range is given as a duration
  15580. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15581. (setq hour (string-to-number (match-string 1 ans))
  15582. h2 (+ hour (string-to-number (match-string 3 ans)))
  15583. minute (string-to-number (match-string 2 ans))
  15584. m2 (+ minute (if (match-end 5) (string-to-number
  15585. (match-string 5 ans))0)))
  15586. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15587. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15588. t t ans)))
  15589. ;; Check if there is a time range
  15590. (when (boundp 'org-end-time-was-given)
  15591. (setq org-time-was-given nil)
  15592. (when (and (string-match org-plain-time-of-day-regexp ans)
  15593. (match-end 8))
  15594. (setq org-end-time-was-given (match-string 8 ans))
  15595. (setq ans (concat (substring ans 0 (match-beginning 7))
  15596. (substring ans (match-end 7))))))
  15597. (setq tl (parse-time-string ans)
  15598. day (or (nth 3 tl) (nth 3 org-defdecode))
  15599. month
  15600. (cond ((nth 4 tl))
  15601. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15602. ;; Day was specified. Make sure DAY+MONTH
  15603. ;; combination happens in the future.
  15604. ((nth 3 tl)
  15605. (setq futurep t)
  15606. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15607. (nth 4 nowdecode)))
  15608. (t (nth 4 org-defdecode)))
  15609. year
  15610. (cond ((and (not kill-year) (nth 5 tl)))
  15611. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15612. ;; Month was guessed in the future and is at least
  15613. ;; equal to NOWDECODE's. Fix year accordingly.
  15614. (futurep
  15615. (if (or (> month (nth 4 nowdecode))
  15616. (>= day (nth 3 nowdecode)))
  15617. (nth 5 nowdecode)
  15618. (1+ (nth 5 nowdecode))))
  15619. ;; Month was specified. Make sure MONTH+YEAR
  15620. ;; combination happens in the future.
  15621. ((nth 4 tl)
  15622. (setq futurep t)
  15623. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15624. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15625. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15626. (t (nth 5 nowdecode))))
  15627. (t (nth 5 org-defdecode)))
  15628. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15629. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15630. second (or (nth 0 tl) 0)
  15631. wday (nth 6 tl))
  15632. (when (and (eq org-read-date-prefer-future 'time)
  15633. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15634. (equal day (nth 3 nowdecode))
  15635. (equal month (nth 4 nowdecode))
  15636. (equal year (nth 5 nowdecode))
  15637. (nth 2 tl)
  15638. (or (< (nth 2 tl) (nth 2 nowdecode))
  15639. (and (= (nth 2 tl) (nth 2 nowdecode))
  15640. (nth 1 tl)
  15641. (< (nth 1 tl) (nth 1 nowdecode)))))
  15642. (setq day (1+ day)
  15643. futurep t))
  15644. ;; Special date definitions below
  15645. (cond
  15646. (iso-week
  15647. ;; There was an iso week
  15648. (require 'cal-iso)
  15649. (setq futurep nil)
  15650. (setq year (or iso-year year)
  15651. day (or iso-weekday wday 1)
  15652. wday nil ; to make sure that the trigger below does not match
  15653. iso-date (calendar-gregorian-from-absolute
  15654. (calendar-iso-to-absolute
  15655. (list iso-week day year))))
  15656. ; FIXME: Should we also push ISO weeks into the future?
  15657. ; (when (and org-read-date-prefer-future
  15658. ; (not iso-year)
  15659. ; (< (calendar-absolute-from-gregorian iso-date)
  15660. ; (time-to-days (current-time))))
  15661. ; (setq year (1+ year)
  15662. ; iso-date (calendar-gregorian-from-absolute
  15663. ; (calendar-iso-to-absolute
  15664. ; (list iso-week day year)))))
  15665. (setq month (car iso-date)
  15666. year (nth 2 iso-date)
  15667. day (nth 1 iso-date)))
  15668. (deltan
  15669. (setq futurep nil)
  15670. (unless deltadef
  15671. ;; Pass `current-time' result to `decode-time' (instead of
  15672. ;; calling without arguments) so that only `current-time' has
  15673. ;; to be overriden in tests.
  15674. (let ((now (decode-time (current-time))))
  15675. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15676. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15677. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15678. ((equal deltaw "m") (setq month (+ month deltan)))
  15679. ((equal deltaw "y") (setq year (+ year deltan)))))
  15680. ((and wday (not (nth 3 tl)))
  15681. ;; Weekday was given, but no day, so pick that day in the week
  15682. ;; on or after the derived date.
  15683. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15684. (unless (equal wday wday1)
  15685. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15686. (when (and (boundp 'org-time-was-given)
  15687. (nth 2 tl))
  15688. (setq org-time-was-given t))
  15689. (when (< year 100) (setq year (+ 2000 year)))
  15690. ;; Check of the date is representable
  15691. (if org-read-date-force-compatible-dates
  15692. (progn
  15693. (when (< year 1970)
  15694. (setq year 1970 org-read-date-analyze-forced-year t))
  15695. (when (> year 2037)
  15696. (setq year 2037 org-read-date-analyze-forced-year t)))
  15697. (condition-case nil
  15698. (ignore (encode-time second minute hour day month year))
  15699. (error
  15700. (setq year (nth 5 org-defdecode))
  15701. (setq org-read-date-analyze-forced-year t))))
  15702. (setq org-read-date-analyze-futurep futurep)
  15703. (list second minute hour day month year)))
  15704. (defvar parse-time-weekdays)
  15705. (defun org-read-date-get-relative (s today default)
  15706. "Check string S for special relative date string.
  15707. TODAY and DEFAULT are internal times, for today and for a default.
  15708. Return shift list (N what def-flag)
  15709. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15710. N is the number of WHATs to shift.
  15711. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15712. the DEFAULT date rather than TODAY."
  15713. (require 'parse-time)
  15714. (when (and
  15715. (string-match
  15716. (concat
  15717. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15718. "\\([0-9]+\\)?"
  15719. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15720. "\\([ \t]\\|$\\)") s)
  15721. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15722. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15723. (string-to-char (substring (match-string 1 s) -1))
  15724. ?+))
  15725. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15726. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15727. (what (if (match-end 3) (match-string 3 s) "d"))
  15728. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15729. (date (if rel default today))
  15730. (wday (nth 6 (decode-time date)))
  15731. delta)
  15732. (if wday1
  15733. (progn
  15734. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15735. (when (= delta 0) (setq delta 7))
  15736. (when (= dir ?-)
  15737. (setq delta (- delta 7))
  15738. (when (= delta 0) (setq delta -7)))
  15739. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15740. (list delta "d" rel))
  15741. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15742. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15743. "Turn a user-specified date into the internal representation.
  15744. The internal representation needed by the calendar is (month day year).
  15745. This is a wrapper to handle the brain-dead convention in calendar that
  15746. user function argument order change dependent on argument order."
  15747. (if (boundp 'calendar-date-style)
  15748. (cond
  15749. ((eq calendar-date-style 'american)
  15750. (list arg1 arg2 arg3))
  15751. ((eq calendar-date-style 'european)
  15752. (list arg2 arg1 arg3))
  15753. ((eq calendar-date-style 'iso)
  15754. (list arg2 arg3 arg1)))
  15755. (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
  15756. (if (org-bound-and-true-p european-calendar-style)
  15757. (list arg2 arg1 arg3)
  15758. (list arg1 arg2 arg3)))))
  15759. (defun org-eval-in-calendar (form &optional keepdate)
  15760. "Eval FORM in the calendar window and return to current window.
  15761. When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
  15762. otherwise stick to the current value of `org-ans2'."
  15763. (let ((sf (selected-frame))
  15764. (sw (selected-window)))
  15765. (select-window (get-buffer-window "*Calendar*" t))
  15766. (eval form)
  15767. (when (and (not keepdate) (calendar-cursor-to-date))
  15768. (let* ((date (calendar-cursor-to-date))
  15769. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15770. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15771. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15772. (select-window sw)
  15773. (org-select-frame-set-input-focus sf)))
  15774. (defun org-calendar-select ()
  15775. "Return to `org-read-date' with the date currently selected.
  15776. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15777. (interactive)
  15778. (when (calendar-cursor-to-date)
  15779. (let* ((date (calendar-cursor-to-date))
  15780. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15781. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15782. (when (active-minibuffer-window) (exit-minibuffer))))
  15783. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15784. "Insert a date stamp for the date given by the internal TIME.
  15785. See `format-time-string' for the format of TIME.
  15786. WITH-HM means use the stamp format that includes the time of the day.
  15787. INACTIVE means use square brackets instead of angular ones, so that the
  15788. stamp will not contribute to the agenda.
  15789. PRE and POST are optional strings to be inserted before and after the
  15790. stamp.
  15791. The command returns the inserted time stamp."
  15792. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15793. stamp)
  15794. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15795. (insert-before-markers (or pre ""))
  15796. (when (listp extra)
  15797. (setq extra (car extra))
  15798. (if (and (stringp extra)
  15799. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15800. (setq extra (format "-%02d:%02d"
  15801. (string-to-number (match-string 1 extra))
  15802. (string-to-number (match-string 2 extra))))
  15803. (setq extra nil)))
  15804. (when extra
  15805. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15806. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15807. (insert-before-markers (or post ""))
  15808. (setq org-last-inserted-timestamp stamp)))
  15809. (defun org-toggle-time-stamp-overlays ()
  15810. "Toggle the use of custom time stamp formats."
  15811. (interactive)
  15812. (setq org-display-custom-times (not org-display-custom-times))
  15813. (unless org-display-custom-times
  15814. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15815. (while (setq p (next-single-property-change p 'display))
  15816. (when (and (get-text-property p 'display)
  15817. (eq (get-text-property p 'face) 'org-date))
  15818. (remove-text-properties
  15819. p (setq p (next-single-property-change p 'display))
  15820. '(display t))))
  15821. (set-buffer-modified-p bmp)))
  15822. (when (featurep 'xemacs)
  15823. (remove-text-properties (point-min) (point-max) '(end-glyph t)))
  15824. (org-restart-font-lock)
  15825. (setq org-table-may-need-update t)
  15826. (if org-display-custom-times
  15827. (message "Time stamps are overlaid with custom format")
  15828. (message "Time stamp overlays removed")))
  15829. (defun org-display-custom-time (beg end)
  15830. "Overlay modified time stamp format over timestamp between BEG and END."
  15831. (let* ((ts (buffer-substring beg end))
  15832. t1 w1 with-hm tf time str w2 (off 0))
  15833. (save-match-data
  15834. (setq t1 (org-parse-time-string ts t))
  15835. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15836. (setq off (- (match-end 0) (match-beginning 0)))))
  15837. (setq end (- end off))
  15838. (setq w1 (- end beg)
  15839. with-hm (and (nth 1 t1) (nth 2 t1))
  15840. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15841. time (org-fix-decoded-time t1)
  15842. str (org-add-props
  15843. (format-time-string
  15844. (substring tf 1 -1) (apply 'encode-time time))
  15845. nil 'mouse-face 'highlight)
  15846. w2 (length str))
  15847. (unless (= w2 w1)
  15848. (add-text-properties (1+ beg) (+ 2 beg)
  15849. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15850. (if (featurep 'xemacs)
  15851. (progn
  15852. (put-text-property beg end 'invisible t)
  15853. (put-text-property beg end 'end-glyph (make-glyph str)))
  15854. (put-text-property beg end 'display str))))
  15855. (defun org-fix-decoded-time (time)
  15856. "Set 0 instead of nil for the first 6 elements of time.
  15857. Don't touch the rest."
  15858. (let ((n 0))
  15859. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15860. (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
  15861. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15862. "Difference between TIMESTAMP-STRING and now in days.
  15863. If SECONDS is non-nil, return the difference in seconds."
  15864. (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
  15865. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15866. (funcall fdiff (current-time)))))
  15867. (defun org-deadline-close (timestamp-string &optional ndays)
  15868. "Is the time in TIMESTAMP-STRING close to the current date?"
  15869. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15870. (and (< (org-time-stamp-to-now timestamp-string) ndays)
  15871. (not (org-entry-is-done-p))))
  15872. (defun org-get-wdays (ts &optional delay zero-delay)
  15873. "Get the deadline lead time appropriate for timestring TS.
  15874. When DELAY is non-nil, get the delay time for scheduled items
  15875. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15876. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15877. don't try to find the delay cookie in the scheduled timestamp."
  15878. (let ((tv (if delay org-scheduled-delay-days
  15879. org-deadline-warning-days)))
  15880. (cond
  15881. ((or (and delay (< tv 0))
  15882. (and delay zero-delay (<= tv 0))
  15883. (and (not delay) (<= tv 0)))
  15884. ;; Enforce this value no matter what
  15885. (- tv))
  15886. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15887. ;; lead time is specified.
  15888. (floor (* (string-to-number (match-string 1 ts))
  15889. (cdr (assoc (match-string 2 ts)
  15890. '(("d" . 1) ("w" . 7)
  15891. ("m" . 30.4) ("y" . 365.25)
  15892. ("h" . 0.041667)))))))
  15893. ;; go for the default.
  15894. (t tv))))
  15895. (defun org-calendar-select-mouse (ev)
  15896. "Return to `org-read-date' with the date currently selected.
  15897. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15898. (interactive "e")
  15899. (mouse-set-point ev)
  15900. (when (calendar-cursor-to-date)
  15901. (let* ((date (calendar-cursor-to-date))
  15902. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15903. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15904. (when (active-minibuffer-window) (exit-minibuffer))))
  15905. (defun org-check-deadlines (ndays)
  15906. "Check if there are any deadlines due or past due.
  15907. A deadline is considered due if it happens within `org-deadline-warning-days'
  15908. days from today's date. If the deadline appears in an entry marked DONE,
  15909. it is not shown. The prefix arg NDAYS can be used to test that many
  15910. days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
  15911. (interactive "P")
  15912. (let* ((org-warn-days
  15913. (cond
  15914. ((equal ndays '(4)) 100000)
  15915. (ndays (prefix-numeric-value ndays))
  15916. (t (abs org-deadline-warning-days))))
  15917. (case-fold-search nil)
  15918. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15919. (callback
  15920. (lambda () (org-deadline-close (match-string 1) org-warn-days))))
  15921. (message "%d deadlines past-due or due within %d days"
  15922. (org-occur regexp nil callback)
  15923. org-warn-days)))
  15924. (defsubst org-re-timestamp (type)
  15925. "Return a regexp for timestamp TYPE.
  15926. Allowed values for TYPE are:
  15927. all: all timestamps
  15928. active: only active timestamps (<...>)
  15929. inactive: only inactive timestamps ([...])
  15930. scheduled: only scheduled timestamps
  15931. deadline: only deadline timestamps
  15932. closed: only closed time-stamps
  15933. When TYPE is nil, fall back on returning a regexp that matches
  15934. both scheduled and deadline timestamps."
  15935. (case type
  15936. (all org-ts-regexp-both)
  15937. (active org-ts-regexp)
  15938. (inactive org-ts-regexp-inactive)
  15939. (scheduled org-scheduled-time-regexp)
  15940. (deadline org-deadline-time-regexp)
  15941. (closed org-closed-time-regexp)
  15942. (otherwise
  15943. (concat "\\<"
  15944. (regexp-opt (list org-deadline-string org-scheduled-string))
  15945. " *<\\([^>]+\\)>"))))
  15946. (defun org-check-before-date (d)
  15947. "Check if there are deadlines or scheduled entries before date D."
  15948. (interactive (list (org-read-date)))
  15949. (let ((case-fold-search nil)
  15950. (regexp (org-re-timestamp org-ts-type))
  15951. (callback
  15952. `(lambda ()
  15953. (let ((match (match-string 1)))
  15954. (and ,(if (memq org-ts-type '(active inactive all))
  15955. '(eq (org-element-type (org-element-context)) 'timestamp)
  15956. '(org-at-planning-p))
  15957. (time-less-p
  15958. (org-time-string-to-time match)
  15959. (org-time-string-to-time d)))))))
  15960. (message "%d entries before %s"
  15961. (org-occur regexp nil callback)
  15962. d)))
  15963. (defun org-check-after-date (d)
  15964. "Check if there are deadlines or scheduled entries after date D."
  15965. (interactive (list (org-read-date)))
  15966. (let ((case-fold-search nil)
  15967. (regexp (org-re-timestamp org-ts-type))
  15968. (callback
  15969. `(lambda ()
  15970. (let ((match (match-string 1)))
  15971. (and ,(if (memq org-ts-type '(active inactive all))
  15972. '(eq (org-element-type (org-element-context)) 'timestamp)
  15973. '(org-at-planning-p))
  15974. (not (time-less-p
  15975. (org-time-string-to-time match)
  15976. (org-time-string-to-time d))))))))
  15977. (message "%d entries after %s"
  15978. (org-occur regexp nil callback)
  15979. d)))
  15980. (defun org-check-dates-range (start-date end-date)
  15981. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15982. (interactive (list (org-read-date nil nil nil "Range starts")
  15983. (org-read-date nil nil nil "Range end")))
  15984. (let ((case-fold-search nil)
  15985. (regexp (org-re-timestamp org-ts-type))
  15986. (callback
  15987. `(lambda ()
  15988. (let ((match (match-string 1)))
  15989. (and
  15990. ,(if (memq org-ts-type '(active inactive all))
  15991. '(eq (org-element-type (org-element-context)) 'timestamp)
  15992. '(org-at-planning-p))
  15993. (not (time-less-p
  15994. (org-time-string-to-time match)
  15995. (org-time-string-to-time start-date)))
  15996. (time-less-p
  15997. (org-time-string-to-time match)
  15998. (org-time-string-to-time end-date)))))))
  15999. (message "%d entries between %s and %s"
  16000. (org-occur regexp nil callback) start-date end-date)))
  16001. (defun org-evaluate-time-range (&optional to-buffer)
  16002. "Evaluate a time range by computing the difference between start and end.
  16003. Normally the result is just printed in the echo area, but with prefix arg
  16004. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16005. If the time range is actually in a table, the result is inserted into the
  16006. next column.
  16007. For time difference computation, a year is assumed to be exactly 365
  16008. days in order to avoid rounding problems."
  16009. (interactive "P")
  16010. (or
  16011. (org-clock-update-time-maybe)
  16012. (save-excursion
  16013. (unless (org-at-date-range-p t)
  16014. (goto-char (point-at-bol))
  16015. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16016. (unless (org-at-date-range-p t)
  16017. (user-error "Not at a time-stamp range, and none found in current line")))
  16018. (let* ((ts1 (match-string 1))
  16019. (ts2 (match-string 2))
  16020. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16021. (match-end (match-end 0))
  16022. (time1 (org-time-string-to-time ts1))
  16023. (time2 (org-time-string-to-time ts2))
  16024. (t1 (org-float-time time1))
  16025. (t2 (org-float-time time2))
  16026. (diff (abs (- t2 t1)))
  16027. (negative (< (- t2 t1) 0))
  16028. ;; (ys (floor (* 365 24 60 60)))
  16029. (ds (* 24 60 60))
  16030. (hs (* 60 60))
  16031. (fy "%dy %dd %02d:%02d")
  16032. (fy1 "%dy %dd")
  16033. (fd "%dd %02d:%02d")
  16034. (fd1 "%dd")
  16035. (fh "%02d:%02d")
  16036. y d h m align)
  16037. (if havetime
  16038. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16039. y 0
  16040. d (floor (/ diff ds)) diff (mod diff ds)
  16041. h (floor (/ diff hs)) diff (mod diff hs)
  16042. m (floor (/ diff 60)))
  16043. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16044. y 0
  16045. d (floor (+ (/ diff ds) 0.5))
  16046. h 0 m 0))
  16047. (if (not to-buffer)
  16048. (message "%s" (org-make-tdiff-string y d h m))
  16049. (if (org-at-table-p)
  16050. (progn
  16051. (goto-char match-end)
  16052. (setq align t)
  16053. (and (looking-at " *|") (goto-char (match-end 0))))
  16054. (goto-char match-end))
  16055. (when (looking-at
  16056. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16057. (replace-match ""))
  16058. (when negative (insert " -"))
  16059. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16060. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16061. (insert " " (format fh h m))))
  16062. (when align (org-table-align))
  16063. (message "Time difference inserted")))))
  16064. (defun org-make-tdiff-string (y d h m)
  16065. (let ((fmt "")
  16066. (l nil))
  16067. (when (> y 0)
  16068. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16069. (push y l))
  16070. (when (> d 0)
  16071. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16072. (push d l))
  16073. (when (> h 0)
  16074. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16075. (push h l))
  16076. (when (> m 0)
  16077. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16078. (push m l))
  16079. (apply 'format fmt (nreverse l))))
  16080. (defun org-time-string-to-time (s &optional buffer pos)
  16081. "Convert a timestamp string into internal time."
  16082. (condition-case errdata
  16083. (apply 'encode-time (org-parse-time-string s))
  16084. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16085. s (if (not (and buffer pos))
  16086. ""
  16087. (format-message " at %d in buffer `%s'" pos buffer))
  16088. (cdr errdata)))))
  16089. (defun org-time-string-to-seconds (s)
  16090. "Convert a timestamp string to a number of seconds."
  16091. (org-float-time (org-time-string-to-time s)))
  16092. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16093. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16094. "Convert time stamp S to an absolute day number.
  16095. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16096. stamp, get the closest date to DAYNR. If PREFER is
  16097. `past' (respectively `future') return a date past (respectively
  16098. after) or equal to DAYNR.
  16099. POS is the location of time stamp S, as a buffer position in
  16100. BUFFER.
  16101. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16102. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16103. signalled."
  16104. (cond
  16105. ((string-match "\\`%%\\((.*)\\)" s)
  16106. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16107. ;; only able to match individual dates. If it fails, raise an
  16108. ;; error.
  16109. (if (and daynr
  16110. (org-diary-sexp-entry
  16111. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16112. daynr
  16113. (signal 'org-diary-sexp-no-match (list s))))
  16114. ((and daynr show-all) (org-closest-date s daynr prefer))
  16115. (t (time-to-days
  16116. (condition-case errdata
  16117. (apply #'encode-time (org-parse-time-string s))
  16118. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16119. s
  16120. (if (not (and buffer pos)) ""
  16121. (format-message " at %d in buffer `%s'" pos buffer))
  16122. (cdr errdata))))))))
  16123. (defun org-days-to-iso-week (days)
  16124. "Return the iso week number."
  16125. (require 'cal-iso)
  16126. (car (calendar-iso-from-absolute days)))
  16127. (defun org-small-year-to-year (year)
  16128. "Convert 2-digit years into 4-digit years.
  16129. YEAR is expanded into one of the 30 next years, if possible, or
  16130. into a past one. Any year larger than 99 is returned unchanged."
  16131. (if (>= year 100) year
  16132. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16133. (century (/ current 100))
  16134. (offset (- year (% current 100))))
  16135. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16136. ((> offset -70) (+ (* century 100) year))
  16137. (t (+ (* (1+ century) 100) year))))))
  16138. (defun org-time-from-absolute (d)
  16139. "Return the time corresponding to date D.
  16140. D may be an absolute day number, or a calendar-type list (month day year)."
  16141. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16142. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16143. (defun org-calendar-holiday ()
  16144. "List of holidays, for Diary display in Org-mode."
  16145. (declare (special date))
  16146. (require 'holidays)
  16147. (let ((hl (funcall
  16148. (if (fboundp 'calendar-check-holidays)
  16149. 'calendar-check-holidays 'check-calendar-holidays) date)))
  16150. (when hl (mapconcat 'identity hl "; "))))
  16151. (defun org-diary-sexp-entry (sexp entry d)
  16152. "Process a SEXP diary ENTRY for date D."
  16153. (require 'diary-lib)
  16154. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16155. ;; dynamically.
  16156. (let* ((sexp `(let ((entry ,entry)
  16157. (date ',d))
  16158. ,(car (read-from-string sexp))))
  16159. (result (if calendar-debug-sexp (eval sexp)
  16160. (condition-case nil
  16161. (eval sexp)
  16162. (error
  16163. (beep)
  16164. (message "Bad sexp at line %d in %s: %s"
  16165. (org-current-line)
  16166. (buffer-file-name) sexp)
  16167. (sleep-for 2))))))
  16168. (cond ((stringp result) (split-string result "; "))
  16169. ((and (consp result)
  16170. (not (consp (cdr result)))
  16171. (stringp (cdr result))) (cdr result))
  16172. ((and (consp result)
  16173. (stringp (car result))) result)
  16174. (result entry))))
  16175. (defun org-diary-to-ical-string (frombuf)
  16176. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16177. This uses the icalendar.el library."
  16178. (let* ((tmpdir (if (featurep 'xemacs)
  16179. (temp-directory)
  16180. temporary-file-directory))
  16181. (tmpfile (make-temp-name
  16182. (expand-file-name "orgics" tmpdir)))
  16183. buf rtn b e)
  16184. (with-current-buffer frombuf
  16185. (icalendar-export-region (point-min) (point-max) tmpfile)
  16186. (setq buf (find-buffer-visiting tmpfile))
  16187. (set-buffer buf)
  16188. (goto-char (point-min))
  16189. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16190. (setq b (match-beginning 0)))
  16191. (goto-char (point-max))
  16192. (when (re-search-backward "^END:VEVENT" nil t)
  16193. (setq e (match-end 0)))
  16194. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16195. (kill-buffer buf)
  16196. (delete-file tmpfile)
  16197. rtn))
  16198. (defun org-closest-date (start current prefer)
  16199. "Return closest date to CURRENT starting from START.
  16200. CURRENT and START are both time stamps.
  16201. When PREFER is `past', return a date that is either CURRENT or
  16202. past. When PREFER is `future', return a date that is either
  16203. CURRENT or future.
  16204. Only time stamps with a repeater are modified. Any other time
  16205. stamp stay unchanged. In any case, return value is an absolute
  16206. day number."
  16207. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16208. ;; No repeater. Do not shift time stamp.
  16209. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16210. (let ((value (string-to-number (match-string 1 start)))
  16211. (type (match-string 2 start)))
  16212. (if (= 0 value)
  16213. ;; Repeater with a 0-value is considered as void.
  16214. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16215. (let* ((base (org-date-to-gregorian start))
  16216. (target (org-date-to-gregorian current))
  16217. (sday (calendar-absolute-from-gregorian base))
  16218. (cday (calendar-absolute-from-gregorian target))
  16219. n1 n2)
  16220. ;; If START is already past CURRENT, just return START.
  16221. (if (<= cday sday) sday
  16222. ;; Compute closest date before (N1) and closest date past
  16223. ;; (N2) CURRENT.
  16224. (pcase type
  16225. ("h"
  16226. (let ((missing-hours
  16227. (mod (+ (- (* 24 (- cday sday))
  16228. (nth 2 (org-parse-time-string start)))
  16229. org-extend-today-until)
  16230. value)))
  16231. (setf n1 (if (= missing-hours 0) cday
  16232. (- cday (1+ (/ missing-hours 24)))))
  16233. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16234. ((or "d" "w")
  16235. (let ((value (if (equal type "w") (* 7 value) value)))
  16236. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16237. (setf n2 (+ n1 value))))
  16238. ("m"
  16239. (let* ((add-months
  16240. (lambda (d n)
  16241. ;; Add N months to gregorian date D, i.e.,
  16242. ;; a list (MONTH DAY YEAR). Return a valid
  16243. ;; gregorian date.
  16244. (let ((m (+ (nth 0 d) n)))
  16245. (list (mod m 12)
  16246. (nth 1 d)
  16247. (+ (/ m 12) (nth 2 d))))))
  16248. (months ; Complete months to TARGET.
  16249. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16250. (- (nth 0 target) (nth 0 base))
  16251. ;; If START's day is greater than
  16252. ;; TARGET's, remove incomplete month.
  16253. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16254. value)
  16255. value))
  16256. (before (funcall add-months base months)))
  16257. (setf n1 (calendar-absolute-from-gregorian before))
  16258. (setf n2
  16259. (calendar-absolute-from-gregorian
  16260. (funcall add-months before value)))))
  16261. (_
  16262. (let* ((d (nth 1 base))
  16263. (m (nth 0 base))
  16264. (y (nth 2 base))
  16265. (years ; Complete years to TARGET.
  16266. (* (/ (- (nth 2 target)
  16267. y
  16268. ;; If START's month and day are
  16269. ;; greater than TARGET's, remove
  16270. ;; incomplete year.
  16271. (if (or (> (nth 0 target) m)
  16272. (and (= (nth 0 target) m)
  16273. (> (nth 1 target) d)))
  16274. 0
  16275. 1))
  16276. value)
  16277. value))
  16278. (before (list m d (+ y years))))
  16279. (setf n1 (calendar-absolute-from-gregorian before))
  16280. (setf n2 (calendar-absolute-from-gregorian
  16281. (list m d (+ (nth 2 before) value)))))))
  16282. ;; Handle PREFER parameter, if any.
  16283. (cond
  16284. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16285. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16286. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16287. (defun org-date-to-gregorian (d)
  16288. "Turn any specification of date D into a Gregorian date for the calendar."
  16289. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16290. ((and (listp d) (= (length d) 3)) d)
  16291. ((stringp d)
  16292. (let ((d (org-parse-time-string d)))
  16293. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16294. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16295. (defun org-parse-time-string (s &optional nodefault)
  16296. "Parse the standard Org-mode time string.
  16297. This should be a lot faster than the normal `parse-time-string'.
  16298. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16299. hour and minute fields will be nil if not given."
  16300. (cond ((string-match org-ts-regexp0 s)
  16301. (list 0
  16302. (when (or (match-beginning 8) (not nodefault))
  16303. (string-to-number (or (match-string 8 s) "0")))
  16304. (when (or (match-beginning 7) (not nodefault))
  16305. (string-to-number (or (match-string 7 s) "0")))
  16306. (string-to-number (match-string 4 s))
  16307. (string-to-number (match-string 3 s))
  16308. (string-to-number (match-string 2 s))
  16309. nil nil nil))
  16310. ((string-match "^<[^>]+>$" s)
  16311. (decode-time (seconds-to-time (org-matcher-time s))))
  16312. (t (error "Not a standard Org-mode time string: %s" s))))
  16313. (defun org-timestamp-up (&optional arg)
  16314. "Increase the date item at the cursor by one.
  16315. If the cursor is on the year, change the year. If it is on the month,
  16316. the day or the time, change that.
  16317. With prefix ARG, change by that many units."
  16318. (interactive "p")
  16319. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16320. (defun org-timestamp-down (&optional arg)
  16321. "Decrease the date item at the cursor by one.
  16322. If the cursor is on the year, change the year. If it is on the month,
  16323. the day or the time, change that.
  16324. With prefix ARG, change by that many units."
  16325. (interactive "p")
  16326. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16327. (defun org-timestamp-up-day (&optional arg)
  16328. "Increase the date in the time stamp by one day.
  16329. With prefix ARG, change that many days."
  16330. (interactive "p")
  16331. (if (and (not (org-at-timestamp-p t))
  16332. (org-at-heading-p))
  16333. (org-todo 'up)
  16334. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16335. (defun org-timestamp-down-day (&optional arg)
  16336. "Decrease the date in the time stamp by one day.
  16337. With prefix ARG, change that many days."
  16338. (interactive "p")
  16339. (if (and (not (org-at-timestamp-p t))
  16340. (org-at-heading-p))
  16341. (org-todo 'down)
  16342. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16343. (defun org-at-timestamp-p (&optional inactive-ok)
  16344. "Non-nil if point is inside a timestamp.
  16345. When optional argument INACTIVE-OK is non-nil, also consider
  16346. inactive timestamps.
  16347. When this function returns a non-nil value, match data is set
  16348. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16349. INACTIVE-OK."
  16350. (interactive)
  16351. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16352. (pos (point))
  16353. (ans (or (looking-at tsr)
  16354. (save-excursion
  16355. (skip-chars-backward "^[<\n\r\t")
  16356. (when (> (point) (point-min)) (backward-char 1))
  16357. (and (looking-at tsr)
  16358. (> (- (match-end 0) pos) -1))))))
  16359. (and ans
  16360. (boundp 'org-ts-what)
  16361. (setq org-ts-what
  16362. (cond
  16363. ((= pos (match-beginning 0)) 'bracket)
  16364. ;; Point is considered to be "on the bracket" whether
  16365. ;; it's really on it or right after it.
  16366. ((= pos (1- (match-end 0))) 'bracket)
  16367. ((= pos (match-end 0)) 'after)
  16368. ((org-pos-in-match-range pos 2) 'year)
  16369. ((org-pos-in-match-range pos 3) 'month)
  16370. ((org-pos-in-match-range pos 7) 'hour)
  16371. ((org-pos-in-match-range pos 8) 'minute)
  16372. ((or (org-pos-in-match-range pos 4)
  16373. (org-pos-in-match-range pos 5)) 'day)
  16374. ((and (> pos (or (match-end 8) (match-end 5)))
  16375. (< pos (match-end 0)))
  16376. (- pos (or (match-end 8) (match-end 5))))
  16377. (t 'day))))
  16378. ans))
  16379. (defun org-toggle-timestamp-type ()
  16380. "Toggle the type (<active> or [inactive]) of a time stamp."
  16381. (interactive)
  16382. (when (org-at-timestamp-p t)
  16383. (let ((beg (match-beginning 0)) (end (match-end 0))
  16384. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16385. (save-excursion
  16386. (goto-char beg)
  16387. (while (re-search-forward "[][<>]" end t)
  16388. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16389. t t)))
  16390. (message "Timestamp is now %sactive"
  16391. (if (equal (char-after beg) ?<) "" "in")))))
  16392. (defun org-at-clock-log-p nil
  16393. "Is the cursor on the clock log line?"
  16394. (save-excursion
  16395. (move-beginning-of-line 1)
  16396. (looking-at org-clock-line-re)))
  16397. (defvar org-clock-history) ; defined in org-clock.el
  16398. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16399. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16400. "Change the date in the time stamp at point.
  16401. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16402. `year', `minute', `second'. If WHAT is not given, the cursor position
  16403. in the timestamp determines what will be changed.
  16404. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16405. (let ((origin (point)) origin-cat
  16406. with-hm inactive
  16407. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16408. org-ts-what
  16409. extra rem
  16410. ts time time0 fixnext clrgx)
  16411. (unless (org-at-timestamp-p t)
  16412. (user-error "Not at a timestamp"))
  16413. (if (and (not what) (eq org-ts-what 'bracket))
  16414. (org-toggle-timestamp-type)
  16415. ;; Point isn't on brackets. Remember the part of the time-stamp
  16416. ;; the point was in. Indeed, size of time-stamps may change,
  16417. ;; but point must be kept in the same category nonetheless.
  16418. (setq origin-cat org-ts-what)
  16419. (when (and (not what) (not (eq org-ts-what 'day))
  16420. org-display-custom-times
  16421. (get-text-property (point) 'display)
  16422. (not (get-text-property (1- (point)) 'display)))
  16423. (setq org-ts-what 'day))
  16424. (setq org-ts-what (or what org-ts-what)
  16425. inactive (= (char-after (match-beginning 0)) ?\[)
  16426. ts (match-string 0))
  16427. (replace-match "")
  16428. (when (string-match
  16429. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16430. ts)
  16431. (setq extra (match-string 1 ts))
  16432. (when suppress-tmp-delay
  16433. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16434. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16435. (setq with-hm t))
  16436. (setq time0 (org-parse-time-string ts))
  16437. (when (and updown
  16438. (eq org-ts-what 'minute)
  16439. (not current-prefix-arg))
  16440. ;; This looks like s-up and s-down. Change by one rounding step.
  16441. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16442. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16443. (setcar (cdr time0) (+ (nth 1 time0)
  16444. (if (> n 0) (- rem) (- dm rem))))))
  16445. (setq time
  16446. (encode-time (or (car time0) 0)
  16447. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16448. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16449. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16450. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16451. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16452. (nthcdr 6 time0)))
  16453. (when (and (member org-ts-what '(hour minute))
  16454. extra
  16455. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16456. (setq extra (org-modify-ts-extra
  16457. extra
  16458. (if (eq org-ts-what 'hour) 2 5)
  16459. n dm)))
  16460. (when (integerp org-ts-what)
  16461. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16462. (when (eq what 'calendar)
  16463. (let ((cal-date (org-get-date-from-calendar)))
  16464. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16465. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16466. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16467. (setcar time0 (or (car time0) 0))
  16468. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16469. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16470. (setq time (apply 'encode-time time0))))
  16471. ;; Insert the new time-stamp, and ensure point stays in the same
  16472. ;; category as before (i.e. not after the last position in that
  16473. ;; category).
  16474. (let ((pos (point)))
  16475. ;; Stay before inserted string. `save-excursion' is of no use.
  16476. (setq org-last-changed-timestamp
  16477. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16478. (goto-char pos))
  16479. (save-match-data
  16480. (looking-at org-ts-regexp3)
  16481. (goto-char (cond
  16482. ;; `day' category ends before `hour' if any, or at
  16483. ;; the end of the day name.
  16484. ((eq origin-cat 'day)
  16485. (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16486. ((eq origin-cat 'hour) (min (match-end 7) origin))
  16487. ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
  16488. ((integerp origin-cat) (min (1- (match-end 0)) origin))
  16489. ;; `year' and `month' have both fixed size: point
  16490. ;; couldn't have moved into another part.
  16491. (t origin))))
  16492. ;; Update clock if on a CLOCK line.
  16493. (org-clock-update-time-maybe)
  16494. ;; Maybe adjust the closest clock in `org-clock-history'
  16495. (when org-clock-adjust-closest
  16496. (if (not (and (org-at-clock-log-p)
  16497. (< 1 (length (delq nil (mapcar 'marker-position
  16498. org-clock-history))))))
  16499. (message "No clock to adjust")
  16500. (cond ((save-excursion ; fix previous clock?
  16501. (re-search-backward org-ts-regexp0 nil t)
  16502. (org-looking-back (concat org-clock-string " \\[")
  16503. (line-beginning-position)))
  16504. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16505. ((save-excursion ; fix next clock?
  16506. (re-search-backward org-ts-regexp0 nil t)
  16507. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16508. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16509. (save-window-excursion
  16510. ;; Find closest clock to point, adjust the previous/next one in history
  16511. (let* ((p (save-excursion (org-back-to-heading t)))
  16512. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16513. (clfixnth
  16514. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16515. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16516. (if (not clfixpos)
  16517. (message "No clock to adjust")
  16518. (save-excursion
  16519. (org-goto-marker-or-bmk clfixpos)
  16520. (org-show-subtree)
  16521. (when (re-search-forward clrgx nil t)
  16522. (goto-char (match-beginning 1))
  16523. (let (org-clock-adjust-closest)
  16524. (org-timestamp-change n org-ts-what updown))
  16525. (message "Clock adjusted in %s for heading: %s"
  16526. (file-name-nondirectory (buffer-file-name))
  16527. (org-get-heading t t)))))))))
  16528. ;; Try to recenter the calendar window, if any.
  16529. (when (and org-calendar-follow-timestamp-change
  16530. (get-buffer-window "*Calendar*" t)
  16531. (memq org-ts-what '(day month year)))
  16532. (org-recenter-calendar (time-to-days time))))))
  16533. (defun org-modify-ts-extra (s pos n dm)
  16534. "Change the different parts of the lead-time and repeat fields in timestamp."
  16535. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16536. ng h m new rem)
  16537. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16538. (cond
  16539. ((or (org-pos-in-match-range pos 2)
  16540. (org-pos-in-match-range pos 3))
  16541. (setq m (string-to-number (match-string 3 s))
  16542. h (string-to-number (match-string 2 s)))
  16543. (if (org-pos-in-match-range pos 2)
  16544. (setq h (+ h n))
  16545. (setq n (* dm (org-no-warnings (signum n))))
  16546. (unless (= 0 (setq rem (% m dm)))
  16547. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16548. (setq m (+ m n)))
  16549. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16550. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16551. (setq h (mod h 24))
  16552. (setq ng 1 new (format "-%02d:%02d" h m)))
  16553. ((org-pos-in-match-range pos 6)
  16554. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16555. ((org-pos-in-match-range pos 5)
  16556. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16557. ((org-pos-in-match-range pos 9)
  16558. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16559. ((org-pos-in-match-range pos 8)
  16560. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16561. (when ng
  16562. (setq s (concat
  16563. (substring s 0 (match-beginning ng))
  16564. new
  16565. (substring s (match-end ng))))))
  16566. s))
  16567. (defun org-recenter-calendar (d)
  16568. "If the calendar is visible, recenter it to date D."
  16569. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16570. (when cwin
  16571. (let ((calendar-move-hook nil))
  16572. (with-selected-window cwin
  16573. (calendar-goto-date
  16574. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16575. (defun org-goto-calendar (&optional arg)
  16576. "Go to the Emacs calendar at the current date.
  16577. If there is a time stamp in the current line, go to that date.
  16578. A prefix ARG can be used to force the current date."
  16579. (interactive "P")
  16580. (let ((tsr org-ts-regexp) diff
  16581. (calendar-move-hook nil)
  16582. (calendar-view-holidays-initially-flag nil)
  16583. (calendar-view-diary-initially-flag nil))
  16584. (when (or (org-at-timestamp-p)
  16585. (save-excursion
  16586. (beginning-of-line 1)
  16587. (looking-at (concat ".*" tsr))))
  16588. (let ((d1 (time-to-days (current-time)))
  16589. (d2 (time-to-days
  16590. (org-time-string-to-time (match-string 1)))))
  16591. (setq diff (- d2 d1))))
  16592. (calendar)
  16593. (calendar-goto-today)
  16594. (when (and diff (not arg)) (calendar-forward-day diff))))
  16595. (defun org-get-date-from-calendar ()
  16596. "Return a list (month day year) of date at point in calendar."
  16597. (with-current-buffer "*Calendar*"
  16598. (save-match-data
  16599. (calendar-cursor-to-date))))
  16600. (defun org-date-from-calendar ()
  16601. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16602. If there is already a time stamp at the cursor position, update it."
  16603. (interactive)
  16604. (if (org-at-timestamp-p t)
  16605. (org-timestamp-change 0 'calendar)
  16606. (let ((cal-date (org-get-date-from-calendar)))
  16607. (org-insert-time-stamp
  16608. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16609. (defcustom org-effort-durations
  16610. `(("min" . 1)
  16611. ("h" . 60)
  16612. ("d" . ,(* 60 8))
  16613. ("w" . ,(* 60 8 5))
  16614. ("m" . ,(* 60 8 5 4))
  16615. ("y" . ,(* 60 8 5 40)))
  16616. "Conversion factor to minutes for an effort modifier.
  16617. Each entry has the form (MODIFIER . MINUTES).
  16618. In an effort string, a number followed by MODIFIER is multiplied
  16619. by the specified number of MINUTES to obtain an effort in
  16620. minutes.
  16621. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16622. effort string \"2hours\" is equivalent to 120 minutes."
  16623. :group 'org-agenda
  16624. :version "25.1"
  16625. :package-version '(Org . "8.3")
  16626. :type '(alist :key-type (string :tag "Modifier")
  16627. :value-type (number :tag "Minutes")))
  16628. (defun org-minutes-to-clocksum-string (m)
  16629. "Format number of minutes as a clocksum string.
  16630. The format is determined by `org-time-clocksum-format',
  16631. `org-time-clocksum-use-fractional' and
  16632. `org-time-clocksum-fractional-format' and
  16633. `org-time-clocksum-use-effort-durations'."
  16634. (let ((clocksum "")
  16635. (m (round m)) ; Don't allow fractions of minutes
  16636. h d w mo y fmt n)
  16637. (setq h (if org-time-clocksum-use-effort-durations
  16638. (cdr (assoc "h" org-effort-durations)) 60)
  16639. d (if org-time-clocksum-use-effort-durations
  16640. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16641. w (if org-time-clocksum-use-effort-durations
  16642. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16643. mo (if org-time-clocksum-use-effort-durations
  16644. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16645. y (if org-time-clocksum-use-effort-durations
  16646. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16647. ;; fractional format
  16648. (if org-time-clocksum-use-fractional
  16649. (cond
  16650. ;; single format string
  16651. ((stringp org-time-clocksum-fractional-format)
  16652. (format org-time-clocksum-fractional-format (/ m (float h))))
  16653. ;; choice of fractional formats for different time units
  16654. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16655. (> (/ (truncate m) (* y d h)) 0))
  16656. (format fmt (/ m (* y d (float h)))))
  16657. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16658. (> (/ (truncate m) (* mo d h)) 0))
  16659. (format fmt (/ m (* mo d (float h)))))
  16660. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16661. (> (/ (truncate m) (* w d h)) 0))
  16662. (format fmt (/ m (* w d (float h)))))
  16663. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16664. (> (/ (truncate m) (* d h)) 0))
  16665. (format fmt (/ m (* d (float h)))))
  16666. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16667. (> (/ (truncate m) h) 0))
  16668. (format fmt (/ m (float h))))
  16669. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16670. (format fmt m))
  16671. ;; fall back to smallest time unit with a format
  16672. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16673. (format fmt (/ m (float h))))
  16674. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16675. (format fmt (/ m (* d (float h)))))
  16676. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16677. (format fmt (/ m (* w d (float h)))))
  16678. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16679. (format fmt (/ m (* mo d (float h)))))
  16680. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16681. (format fmt (/ m (* y d (float h))))))
  16682. ;; standard (non-fractional) format, with single format string
  16683. (if (stringp org-time-clocksum-format)
  16684. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16685. ;; separate formats components
  16686. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16687. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16688. (plist-get org-time-clocksum-format :require-years))
  16689. (setq clocksum (concat clocksum (format fmt n))
  16690. m (- m (* n y d h))))
  16691. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16692. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16693. (plist-get org-time-clocksum-format :require-months))
  16694. (setq clocksum (concat clocksum (format fmt n))
  16695. m (- m (* n mo d h))))
  16696. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16697. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16698. (plist-get org-time-clocksum-format :require-weeks))
  16699. (setq clocksum (concat clocksum (format fmt n))
  16700. m (- m (* n w d h))))
  16701. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16702. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16703. (plist-get org-time-clocksum-format :require-days))
  16704. (setq clocksum (concat clocksum (format fmt n))
  16705. m (- m (* n d h))))
  16706. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16707. (or (> (setq n (/ (truncate m) h)) 0)
  16708. (plist-get org-time-clocksum-format :require-hours))
  16709. (setq clocksum (concat clocksum (format fmt n))
  16710. m (- m (* n h))))
  16711. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16712. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16713. (setq clocksum (concat clocksum (format fmt m))))
  16714. ;; return formatted time duration
  16715. clocksum))))
  16716. (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
  16717. (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
  16718. "Org mode version 8.0")
  16719. (defun org-hours-to-clocksum-string (n)
  16720. (org-minutes-to-clocksum-string (* n 60)))
  16721. (defun org-hh:mm-string-to-minutes (s)
  16722. "Convert a string H:MM to a number of minutes.
  16723. If the string is just a number, interpret it as minutes.
  16724. In fact, the first hh:mm or number in the string will be taken,
  16725. there can be extra stuff in the string.
  16726. If no number is found, the return value is 0."
  16727. (cond
  16728. ((integerp s) s)
  16729. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16730. (+ (* (string-to-number (match-string 1 s)) 60)
  16731. (string-to-number (match-string 2 s))))
  16732. ((string-match "\\([0-9]+\\)" s)
  16733. (string-to-number (match-string 1 s)))
  16734. (t 0)))
  16735. (defcustom org-image-actual-width t
  16736. "Should we use the actual width of images when inlining them?
  16737. When set to t, always use the image width.
  16738. When set to a number, use imagemagick (when available) to set
  16739. the image's width to this value.
  16740. When set to a number in a list, try to get the width from any
  16741. #+ATTR.* keyword if it matches a width specification like
  16742. #+ATTR_HTML: :width 300px
  16743. and fall back on that number if none is found.
  16744. When set to nil, try to get the width from an #+ATTR.* keyword
  16745. and fall back on the original width if none is found.
  16746. This requires Emacs >= 24.1, build with imagemagick support."
  16747. :group 'org-appearance
  16748. :version "24.4"
  16749. :package-version '(Org . "8.0")
  16750. :type '(choice
  16751. (const :tag "Use the image width" t)
  16752. (integer :tag "Use a number of pixels")
  16753. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16754. (const :tag "Use #+ATTR* or don't resize" nil)))
  16755. (defcustom org-agenda-inhibit-startup nil
  16756. "Inhibit startup when preparing agenda buffers.
  16757. When this variable is t, the initialization of the Org agenda
  16758. buffers is inhibited: e.g. the visibility state is not set, the
  16759. tables are not re-aligned, etc."
  16760. :type 'boolean
  16761. :version "24.3"
  16762. :group 'org-agenda)
  16763. (define-obsolete-variable-alias
  16764. 'org-agenda-ignore-drawer-properties
  16765. 'org-agenda-ignore-properties "25.1")
  16766. (defcustom org-agenda-ignore-properties nil
  16767. "Avoid updating text properties when building the agenda.
  16768. Properties are used to prepare buffers for effort estimates,
  16769. appointments, statistics and subtree-local categories.
  16770. If you don't use these in the agenda, you can add them to this
  16771. list and agenda building will be a bit faster.
  16772. The value is a list, with zero or more of the symbols `effort', `appt',
  16773. `stats' or `category'."
  16774. :type '(set :greedy t
  16775. (const effort)
  16776. (const appt)
  16777. (const stats)
  16778. (const category))
  16779. :version "25.1"
  16780. :package-version '(Org . "8.3")
  16781. :group 'org-agenda)
  16782. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16783. "Convert a duration string S to minutes.
  16784. A bare number is interpreted as minutes, modifiers can be set by
  16785. customizing `org-effort-durations' (which see).
  16786. Entries containing a colon are interpreted as H:MM by
  16787. `org-hh:mm-string-to-minutes'."
  16788. (let ((result 0)
  16789. (re (concat "\\([0-9.]+\\) *\\("
  16790. (regexp-opt (mapcar 'car org-effort-durations))
  16791. "\\)")))
  16792. (while (string-match re s)
  16793. (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16794. (string-to-number (match-string 1 s))))
  16795. (setq s (replace-match "" nil t s)))
  16796. (setq result (floor result))
  16797. (incf result (org-hh:mm-string-to-minutes s))
  16798. (if output-to-string (number-to-string result) result)))
  16799. ;;;; Files
  16800. (defun org-save-all-org-buffers ()
  16801. "Save all Org-mode buffers without user confirmation."
  16802. (interactive)
  16803. (message "Saving all Org-mode buffers...")
  16804. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16805. (when (featurep 'org-id) (org-id-locations-save))
  16806. (message "Saving all Org-mode buffers... done"))
  16807. (defun org-revert-all-org-buffers ()
  16808. "Revert all Org-mode buffers.
  16809. Prompt for confirmation when there are unsaved changes.
  16810. Be sure you know what you are doing before letting this function
  16811. overwrite your changes.
  16812. This function is useful in a setup where one tracks org files
  16813. with a version control system, to revert on one machine after pulling
  16814. changes from another. I believe the procedure must be like this:
  16815. 1. M-x org-save-all-org-buffers
  16816. 2. Pull changes from the other machine, resolve conflicts
  16817. 3. M-x org-revert-all-org-buffers"
  16818. (interactive)
  16819. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16820. (user-error "Abort"))
  16821. (save-excursion
  16822. (save-window-excursion
  16823. (mapc
  16824. (lambda (b)
  16825. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16826. (with-current-buffer b buffer-file-name))
  16827. (org-pop-to-buffer-same-window b)
  16828. (revert-buffer t 'no-confirm)))
  16829. (buffer-list))
  16830. (when (and (featurep 'org-id) org-id-track-globally)
  16831. (org-id-locations-load)))))
  16832. ;;;; Agenda files
  16833. ;;;###autoload
  16834. (defun org-switchb (&optional arg)
  16835. "Switch between Org buffers.
  16836. With one prefix argument, restrict available buffers to files.
  16837. With two prefix arguments, restrict available buffers to agenda files.
  16838. Defaults to `iswitchb' for buffer name completion.
  16839. Set `org-completion-use-ido' to make it use ido instead."
  16840. (interactive "P")
  16841. (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
  16842. ((equal arg '(16)) (org-buffer-list 'agenda))
  16843. (t (org-buffer-list))))
  16844. (org-completion-use-iswitchb org-completion-use-iswitchb)
  16845. (org-completion-use-ido org-completion-use-ido))
  16846. (unless (or org-completion-use-ido org-completion-use-iswitchb)
  16847. (setq org-completion-use-iswitchb t))
  16848. (org-pop-to-buffer-same-window
  16849. (completing-read "Org buffer: "
  16850. (mapcar #'list (mapcar #'buffer-name blist))
  16851. nil t))))
  16852. ;;; Define some older names previously used for this functionality
  16853. ;;;###autoload
  16854. (defalias 'org-ido-switchb 'org-switchb)
  16855. ;;;###autoload
  16856. (defalias 'org-iswitchb 'org-switchb)
  16857. (defun org-buffer-list (&optional predicate exclude-tmp)
  16858. "Return a list of Org buffers.
  16859. PREDICATE can be `export', `files' or `agenda'.
  16860. export restrict the list to Export buffers.
  16861. files restrict the list to buffers visiting Org files.
  16862. agenda restrict the list to buffers visiting agenda files.
  16863. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16864. (let* ((bfn nil)
  16865. (agenda-files (and (eq predicate 'agenda)
  16866. (mapcar 'file-truename (org-agenda-files t))))
  16867. (filter
  16868. (cond
  16869. ((eq predicate 'files)
  16870. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16871. ((eq predicate 'export)
  16872. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16873. ((eq predicate 'agenda)
  16874. (lambda (b)
  16875. (with-current-buffer b
  16876. (and (derived-mode-p 'org-mode)
  16877. (setq bfn (buffer-file-name b))
  16878. (member (file-truename bfn) agenda-files)))))
  16879. (t (lambda (b) (with-current-buffer b
  16880. (or (derived-mode-p 'org-mode)
  16881. (string-match "\\*Org .*Export"
  16882. (buffer-name b)))))))))
  16883. (delq nil
  16884. (mapcar
  16885. (lambda(b)
  16886. (if (and (funcall filter b)
  16887. (or (not exclude-tmp)
  16888. (not (string-match "tmp" (buffer-name b)))))
  16889. b
  16890. nil))
  16891. (buffer-list)))))
  16892. (defun org-agenda-files (&optional unrestricted archives)
  16893. "Get the list of agenda files.
  16894. Optional UNRESTRICTED means return the full list even if a restriction
  16895. is currently in place.
  16896. When ARCHIVES is t, include all archive files that are really being
  16897. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16898. `org-agenda-archives-mode' is t."
  16899. (let ((files
  16900. (cond
  16901. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16902. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16903. ((listp org-agenda-files) org-agenda-files)
  16904. (t (error "Invalid value of `org-agenda-files'")))))
  16905. (setq files (apply 'append
  16906. (mapcar (lambda (f)
  16907. (if (file-directory-p f)
  16908. (directory-files
  16909. f t org-agenda-file-regexp)
  16910. (list f)))
  16911. files)))
  16912. (when org-agenda-skip-unavailable-files
  16913. (setq files (delq nil
  16914. (mapcar (function
  16915. (lambda (file)
  16916. (and (file-readable-p file) file)))
  16917. files))))
  16918. (when (or (eq archives t)
  16919. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16920. (setq files (org-add-archive-files files)))
  16921. files))
  16922. (defun org-agenda-file-p (&optional file)
  16923. "Return non-nil, if FILE is an agenda file.
  16924. If FILE is omitted, use the file associated with the current
  16925. buffer."
  16926. (let ((fname (or file (buffer-file-name))))
  16927. (and fname
  16928. (member (file-truename fname)
  16929. (mapcar #'file-truename (org-agenda-files t))))))
  16930. (defun org-edit-agenda-file-list ()
  16931. "Edit the list of agenda files.
  16932. Depending on setup, this either uses customize to edit the variable
  16933. `org-agenda-files', or it visits the file that is holding the list. In the
  16934. latter case, the buffer is set up in a way that saving it automatically kills
  16935. the buffer and restores the previous window configuration."
  16936. (interactive)
  16937. (if (stringp org-agenda-files)
  16938. (let ((cw (current-window-configuration)))
  16939. (find-file org-agenda-files)
  16940. (setq-local org-window-configuration cw)
  16941. (org-add-hook 'after-save-hook
  16942. (lambda ()
  16943. (set-window-configuration
  16944. (prog1 org-window-configuration
  16945. (kill-buffer (current-buffer))))
  16946. (org-install-agenda-files-menu)
  16947. (message "New agenda file list installed"))
  16948. nil 'local)
  16949. (message "%s" (substitute-command-keys
  16950. "Edit list and finish with \\[save-buffer]")))
  16951. (customize-variable 'org-agenda-files)))
  16952. (defun org-store-new-agenda-file-list (list)
  16953. "Set new value for the agenda file list and save it correctly."
  16954. (if (stringp org-agenda-files)
  16955. (let ((fe (org-read-agenda-file-list t)) b u)
  16956. (while (setq b (find-buffer-visiting org-agenda-files))
  16957. (kill-buffer b))
  16958. (with-temp-file org-agenda-files
  16959. (insert
  16960. (mapconcat
  16961. (lambda (f) ;; Keep un-expanded entries.
  16962. (if (setq u (assoc f fe))
  16963. (cdr u)
  16964. f))
  16965. list "\n")
  16966. "\n")))
  16967. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16968. (org-insert-mode-line-in-empty-file nil))
  16969. (setq org-agenda-files list)
  16970. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16971. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16972. "Read the list of agenda files from a file.
  16973. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16974. filenames, used by `org-store-new-agenda-file-list' to write back
  16975. un-expanded file names."
  16976. (when (file-directory-p org-agenda-files)
  16977. (error "`org-agenda-files' cannot be a single directory"))
  16978. (when (stringp org-agenda-files)
  16979. (with-temp-buffer
  16980. (insert-file-contents org-agenda-files)
  16981. (mapcar
  16982. (lambda (f)
  16983. (let ((e (expand-file-name (substitute-in-file-name f)
  16984. org-directory)))
  16985. (if pair-with-expansion
  16986. (cons e f)
  16987. e)))
  16988. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16989. ;;;###autoload
  16990. (defun org-cycle-agenda-files ()
  16991. "Cycle through the files in `org-agenda-files'.
  16992. If the current buffer visits an agenda file, find the next one in the list.
  16993. If the current buffer does not, find the first agenda file."
  16994. (interactive)
  16995. (let* ((fs (or (org-agenda-files t)
  16996. (user-error "No agenda files")))
  16997. (files (copy-sequence fs))
  16998. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16999. file)
  17000. (when tcf
  17001. (while (and (setq file (pop files))
  17002. (not (equal (file-truename file) tcf)))))
  17003. (find-file (car (or files fs)))
  17004. (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
  17005. (defun org-agenda-file-to-front (&optional to-end)
  17006. "Move/add the current file to the top of the agenda file list.
  17007. If the file is not present in the list, it is added to the front. If it is
  17008. present, it is moved there. With optional argument TO-END, add/move to the
  17009. end of the list."
  17010. (interactive "P")
  17011. (let ((org-agenda-skip-unavailable-files nil)
  17012. (file-alist (mapcar (lambda (x)
  17013. (cons (file-truename x) x))
  17014. (org-agenda-files t)))
  17015. (ctf (file-truename
  17016. (or buffer-file-name
  17017. (user-error "Please save the current buffer to a file"))))
  17018. x had)
  17019. (setq x (assoc ctf file-alist) had x)
  17020. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17021. (if to-end
  17022. (setq file-alist (append (delq x file-alist) (list x)))
  17023. (setq file-alist (cons x (delq x file-alist))))
  17024. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17025. (org-install-agenda-files-menu)
  17026. (message "File %s to %s of agenda file list"
  17027. (if had "moved" "added") (if to-end "end" "front"))))
  17028. (defun org-remove-file (&optional file)
  17029. "Remove current file from the list of files in variable `org-agenda-files'.
  17030. These are the files which are being checked for agenda entries.
  17031. Optional argument FILE means use this file instead of the current."
  17032. (interactive)
  17033. (let* ((org-agenda-skip-unavailable-files nil)
  17034. (file (or file buffer-file-name
  17035. (user-error "Current buffer does not visit a file")))
  17036. (true-file (file-truename file))
  17037. (afile (abbreviate-file-name file))
  17038. (files (delq nil (mapcar
  17039. (lambda (x)
  17040. (unless (equal true-file
  17041. (file-truename x))
  17042. x))
  17043. (org-agenda-files t)))))
  17044. (if (not (= (length files) (length (org-agenda-files t))))
  17045. (progn
  17046. (org-store-new-agenda-file-list files)
  17047. (org-install-agenda-files-menu)
  17048. (message "Removed from Org Agenda list: %s" afile))
  17049. (message "File was not in list: %s (not removed)" afile))))
  17050. (defun org-file-menu-entry (file)
  17051. (vector file (list 'find-file file) t))
  17052. (defun org-check-agenda-file (file)
  17053. "Make sure FILE exists. If not, ask user what to do."
  17054. (unless (file-exists-p file)
  17055. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17056. (abbreviate-file-name file))
  17057. (let ((r (downcase (read-char-exclusive))))
  17058. (cond
  17059. ((equal r ?r)
  17060. (org-remove-file file)
  17061. (throw 'nextfile t))
  17062. (t (user-error "Abort"))))))
  17063. (defun org-get-agenda-file-buffer (file)
  17064. "Get an agenda buffer visiting FILE.
  17065. If the buffer needs to be created, add it to the list of buffers
  17066. which might be released later."
  17067. (let ((buf (org-find-base-buffer-visiting file)))
  17068. (if buf
  17069. buf ; just return it
  17070. ;; Make a new buffer and remember it
  17071. (setq buf (find-file-noselect file))
  17072. (when buf (push buf org-agenda-new-buffers))
  17073. buf)))
  17074. (defun org-release-buffers (blist)
  17075. "Release all buffers in list, asking the user for confirmation when needed.
  17076. When a buffer is unmodified, it is just killed. When modified, it is saved
  17077. \(if the user agrees) and then killed."
  17078. (let (file)
  17079. (dolist (buf blist)
  17080. (setq file (buffer-file-name buf))
  17081. (when (and (buffer-modified-p buf)
  17082. file
  17083. (y-or-n-p (format "Save file %s? " file)))
  17084. (with-current-buffer buf (save-buffer)))
  17085. (kill-buffer buf))))
  17086. (defun org-agenda-prepare-buffers (files)
  17087. "Create buffers for all agenda files, protect archived trees and comments."
  17088. (interactive)
  17089. (let ((pa '(:org-archived t))
  17090. (pc '(:org-comment t))
  17091. (pall '(:org-archived t :org-comment t))
  17092. (inhibit-read-only t)
  17093. (org-inhibit-startup org-agenda-inhibit-startup)
  17094. (rea (concat ":" org-archive-tag ":"))
  17095. re pos)
  17096. (setq org-tag-alist-for-agenda nil
  17097. org-tag-groups-alist-for-agenda nil)
  17098. (save-excursion
  17099. (save-restriction
  17100. (dolist (file files)
  17101. (catch 'nextfile
  17102. (if (bufferp file)
  17103. (set-buffer file)
  17104. (org-check-agenda-file file)
  17105. (set-buffer (org-get-agenda-file-buffer file)))
  17106. (widen)
  17107. (org-set-regexps-and-options 'tags-only)
  17108. (setq pos (point))
  17109. (or (memq 'category org-agenda-ignore-properties)
  17110. (org-refresh-category-properties))
  17111. (or (memq 'stats org-agenda-ignore-properties)
  17112. (org-refresh-stats-properties))
  17113. (or (memq 'effort org-agenda-ignore-properties)
  17114. (org-refresh-effort-properties))
  17115. (or (memq 'appt org-agenda-ignore-properties)
  17116. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17117. (setq org-todo-keywords-for-agenda
  17118. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17119. (setq org-done-keywords-for-agenda
  17120. (append org-done-keywords-for-agenda org-done-keywords))
  17121. (setq org-todo-keyword-alist-for-agenda
  17122. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17123. (setq org-tag-alist-for-agenda
  17124. (org-uniquify
  17125. (append org-tag-alist-for-agenda
  17126. org-tag-alist
  17127. org-tag-persistent-alist)))
  17128. (when org-group-tags
  17129. (setq org-tag-groups-alist-for-agenda
  17130. (org-uniquify-alist
  17131. (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
  17132. (org-with-silent-modifications
  17133. (save-excursion
  17134. (remove-text-properties (point-min) (point-max) pall)
  17135. (when org-agenda-skip-archived-trees
  17136. (goto-char (point-min))
  17137. (while (re-search-forward rea nil t)
  17138. (when (org-at-heading-p t)
  17139. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17140. (goto-char (point-min))
  17141. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17142. (while (re-search-forward re nil t)
  17143. (when (save-match-data (org-in-commented-heading-p t))
  17144. (add-text-properties
  17145. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17146. (goto-char pos)))))
  17147. (setq org-todo-keywords-for-agenda
  17148. (org-uniquify org-todo-keywords-for-agenda))
  17149. (setq org-todo-keyword-alist-for-agenda
  17150. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17151. ;;;; CDLaTeX minor mode
  17152. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17153. "Keymap for the minor `org-cdlatex-mode'.")
  17154. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17155. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17156. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17157. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17158. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17159. (defvar org-cdlatex-texmathp-advice-is-done nil
  17160. "Flag remembering if we have applied the advice to texmathp already.")
  17161. (define-minor-mode org-cdlatex-mode
  17162. "Toggle the minor `org-cdlatex-mode'.
  17163. This mode supports entering LaTeX environment and math in LaTeX fragments
  17164. in Org-mode.
  17165. \\{org-cdlatex-mode-map}"
  17166. nil " OCDL" nil
  17167. (when org-cdlatex-mode
  17168. (require 'cdlatex)
  17169. (run-hooks 'cdlatex-mode-hook)
  17170. (cdlatex-compute-tables))
  17171. (unless org-cdlatex-texmathp-advice-is-done
  17172. (setq org-cdlatex-texmathp-advice-is-done t)
  17173. (defadvice texmathp (around org-math-always-on activate)
  17174. "Always return t in org-mode buffers.
  17175. This is because we want to insert math symbols without dollars even outside
  17176. the LaTeX math segments. If Orgmode thinks that point is actually inside
  17177. an embedded LaTeX fragment, let texmathp do its job.
  17178. \\[org-cdlatex-mode-map]"
  17179. (interactive)
  17180. (let (p)
  17181. (cond
  17182. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17183. ((eq this-command 'cdlatex-math-symbol)
  17184. (setq ad-return-value t
  17185. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17186. (t
  17187. (let ((p (org-inside-LaTeX-fragment-p)))
  17188. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17189. (setq ad-return-value t
  17190. texmathp-why '("Org-mode embedded math" . 0))
  17191. (when p ad-do-it)))))))))
  17192. (defun turn-on-org-cdlatex ()
  17193. "Unconditionally turn on `org-cdlatex-mode'."
  17194. (org-cdlatex-mode 1))
  17195. (defun org-try-cdlatex-tab ()
  17196. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17197. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17198. - inside a LaTeX fragment, or
  17199. - after the first word in a line, where an abbreviation expansion could
  17200. insert a LaTeX environment."
  17201. (when org-cdlatex-mode
  17202. (cond
  17203. ;; Before any word on the line: No expansion possible.
  17204. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17205. ;; Just after first word on the line: Expand it. Make sure it
  17206. ;; cannot happen on headlines, though.
  17207. ((save-excursion
  17208. (skip-chars-backward "a-zA-Z0-9*")
  17209. (skip-chars-backward " \t")
  17210. (and (bolp) (not (org-at-heading-p))))
  17211. (cdlatex-tab) t)
  17212. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17213. (defun org-cdlatex-underscore-caret (&optional _arg)
  17214. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17215. Revert to the normal definition outside of these fragments."
  17216. (interactive "P")
  17217. (if (org-inside-LaTeX-fragment-p)
  17218. (call-interactively 'cdlatex-sub-superscript)
  17219. (let (org-cdlatex-mode)
  17220. (call-interactively (key-binding (vector last-input-event))))))
  17221. (defun org-cdlatex-math-modify (&optional _arg)
  17222. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17223. Revert to the normal definition outside of these fragments."
  17224. (interactive "P")
  17225. (if (org-inside-LaTeX-fragment-p)
  17226. (call-interactively 'cdlatex-math-modify)
  17227. (let (org-cdlatex-mode)
  17228. (call-interactively (key-binding (vector last-input-event))))))
  17229. (defun org-cdlatex-environment-indent (&optional environment item)
  17230. "Execute `cdlatex-environment' and indent the inserted environment.
  17231. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17232. The inserted environment is indented to current indentation
  17233. unless point is at the beginning of the line, in which the
  17234. environment remains unintended."
  17235. (interactive)
  17236. ;; cdlatex-environment always return nil. Therefore, capture output
  17237. ;; first and determine if an environment was selected.
  17238. (let* ((beg (point-marker))
  17239. (end (copy-marker (point) t))
  17240. (inserted (progn
  17241. (ignore-errors (cdlatex-environment environment item))
  17242. (< beg end)))
  17243. ;; Figure out how many lines to move forward after the
  17244. ;; environment has been inserted.
  17245. (lines (when inserted
  17246. (save-excursion
  17247. (- (loop while (< beg (point))
  17248. with x = 0
  17249. do (forward-line -1)
  17250. (incf x)
  17251. finally return x)
  17252. (if (progn (goto-char beg)
  17253. (and (progn (skip-chars-forward " \t") (eolp))
  17254. (progn (skip-chars-backward " \t") (bolp))))
  17255. 1 0)))))
  17256. (env (org-trim (delete-and-extract-region beg end))))
  17257. (when inserted
  17258. ;; Get indentation of next line unless at column 0.
  17259. (let ((ind (if (bolp) 0
  17260. (save-excursion
  17261. (org-return-indent)
  17262. (prog1 (org-get-indentation)
  17263. (when (progn (skip-chars-forward " \t") (eolp))
  17264. (delete-region beg (point)))))))
  17265. (bol (progn (skip-chars-backward " \t") (bolp))))
  17266. ;; Insert a newline before environment unless at column zero
  17267. ;; to "escape" the current line. Insert a newline if
  17268. ;; something is one the same line as \end{ENVIRONMENT}.
  17269. (insert
  17270. (concat (unless bol "\n") env
  17271. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17272. (unless (zerop ind)
  17273. (save-excursion
  17274. (goto-char beg)
  17275. (while (< (point) end)
  17276. (unless (eolp) (org-indent-line-to ind))
  17277. (forward-line))))
  17278. (goto-char beg)
  17279. (forward-line lines)
  17280. (org-indent-line-to ind)))
  17281. (set-marker beg nil)
  17282. (set-marker end nil)))
  17283. ;;;; LaTeX fragments
  17284. (defun org-inside-LaTeX-fragment-p ()
  17285. "Test if point is inside a LaTeX fragment.
  17286. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17287. sequence appearing also before point.
  17288. Even though the matchers for math are configurable, this function assumes
  17289. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17290. delimiters are skipped when they have been removed by customization.
  17291. The return value is nil, or a cons cell with the delimiter and the
  17292. position of this delimiter.
  17293. This function does a reasonably good job, but can locally be fooled by
  17294. for example currency specifications. For example it will assume being in
  17295. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17296. fragments that are properly closed, but during editing, we have to live
  17297. with the uncertainty caused by missing closing delimiters. This function
  17298. looks only before point, not after."
  17299. (catch 'exit
  17300. (let ((pos (point))
  17301. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17302. (lim (progn
  17303. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17304. (point)))
  17305. dd-on str (start 0) m re)
  17306. (goto-char pos)
  17307. (when dodollar
  17308. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17309. re (nth 1 (assoc "$" org-latex-regexps)))
  17310. (while (string-match re str start)
  17311. (cond
  17312. ((= (match-end 0) (length str))
  17313. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17314. ((= (match-end 0) (- (length str) 5))
  17315. (throw 'exit nil))
  17316. (t (setq start (match-end 0))))))
  17317. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17318. (goto-char pos)
  17319. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17320. (and (match-beginning 2) (throw 'exit nil))
  17321. ;; count $$
  17322. (while (re-search-backward "\\$\\$" lim t)
  17323. (setq dd-on (not dd-on)))
  17324. (goto-char pos)
  17325. (when dd-on (cons "$$" m))))))
  17326. (defun org-inside-latex-macro-p ()
  17327. "Is point inside a LaTeX macro or its arguments?"
  17328. (save-match-data
  17329. (org-in-regexp
  17330. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17331. (defvar-local org-latex-fragment-image-overlays nil
  17332. "List of overlays carrying the images of latex fragments.")
  17333. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17334. "Remove all overlays with LaTeX fragment images in current buffer.
  17335. When optional arguments BEG and END are non-nil, remove all
  17336. overlays between them instead. Return t when some overlays were
  17337. removed, nil otherwise."
  17338. (let (removedp)
  17339. (setq org-latex-fragment-image-overlays
  17340. (let ((beg (or beg (point-min)))
  17341. (end (or end (point-max))))
  17342. (cl-remove-if
  17343. (lambda (o)
  17344. (cond ((not (overlay-buffer o)) (delete-overlay o) t)
  17345. ((and (>= (overlay-start o) beg)
  17346. (<= (overlay-end o) end))
  17347. (delete-overlay o)
  17348. (unless removedp (setq removedp t)))
  17349. (t nil)))
  17350. org-latex-fragment-image-overlays)))
  17351. removedp))
  17352. (define-obsolete-function-alias
  17353. 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
  17354. (defun org-toggle-latex-fragment (&optional arg)
  17355. "Preview the LaTeX fragment at point, or all locally or globally.
  17356. If the cursor is on a LaTeX fragment, create the image and overlay
  17357. it over the source code, if there is none. Remove it otherwise.
  17358. If there is no fragment at point, display all fragments in the
  17359. current section.
  17360. With prefix ARG, preview or clear image for all fragments in the
  17361. current subtree or in the whole buffer when used before the first
  17362. headline. With a double prefix ARG \\[universal-argument] \
  17363. \\[universal-argument] preview or clear images
  17364. for all fragments in the buffer."
  17365. (interactive "P")
  17366. (unless (buffer-file-name (buffer-base-buffer))
  17367. (user-error "Can't preview LaTeX fragment in a non-file buffer"))
  17368. (when (display-graphic-p)
  17369. (catch 'exit
  17370. (save-excursion
  17371. (let ((window-start (window-start)) msg)
  17372. (save-restriction
  17373. (cond
  17374. ((or (equal arg '(16))
  17375. (and (equal arg '(4))
  17376. (org-with-limited-levels (org-before-first-heading-p))))
  17377. (if (org-remove-latex-fragment-image-overlays)
  17378. (progn (message "LaTeX fragments images removed from buffer")
  17379. (throw 'exit nil))
  17380. (setq msg "Creating images for buffer...")))
  17381. ((equal arg '(4))
  17382. (org-with-limited-levels (org-back-to-heading t))
  17383. (let ((beg (point))
  17384. (end (progn (org-end-of-subtree t) (point))))
  17385. (if (org-remove-latex-fragment-image-overlays beg end)
  17386. (progn
  17387. (message "LaTeX fragment images removed from subtree")
  17388. (throw 'exit nil))
  17389. (setq msg "Creating images for subtree...")
  17390. (narrow-to-region beg end))))
  17391. ((let ((datum (org-element-context)))
  17392. (when (memq (org-element-type datum)
  17393. '(latex-environment latex-fragment))
  17394. (let* ((beg (org-element-property :begin datum))
  17395. (end (org-element-property :end datum)))
  17396. (if (org-remove-latex-fragment-image-overlays beg end)
  17397. (progn (message "LaTeX fragment image removed")
  17398. (throw 'exit nil))
  17399. (narrow-to-region beg end)
  17400. (setq msg "Creating image..."))))))
  17401. (t
  17402. (org-with-limited-levels
  17403. (let ((beg (if (org-at-heading-p) (line-beginning-position)
  17404. (outline-previous-heading)
  17405. (point)))
  17406. (end (progn (outline-next-heading) (point))))
  17407. (if (org-remove-latex-fragment-image-overlays beg end)
  17408. (progn
  17409. (message "LaTeX fragment images removed from section")
  17410. (throw 'exit nil))
  17411. (setq msg "Creating images for section...")
  17412. (narrow-to-region beg end))))))
  17413. (let ((file (buffer-file-name (buffer-base-buffer))))
  17414. (org-format-latex
  17415. (concat org-latex-preview-ltxpng-directory
  17416. (file-name-sans-extension (file-name-nondirectory file)))
  17417. ;; Emacs cannot overlay images from remote hosts.
  17418. ;; Create it in `temporary-file-directory' instead.
  17419. (if (file-remote-p file) temporary-file-directory
  17420. default-directory)
  17421. 'overlays msg 'forbuffer
  17422. org-latex-create-formula-image-program)))
  17423. ;; Work around a bug that doesn't restore window's start
  17424. ;; when widening back the buffer.
  17425. (set-window-start nil window-start)
  17426. (message (concat msg "done")))))))
  17427. (defun org-format-latex
  17428. (prefix &optional dir overlays msg forbuffer processing-type)
  17429. "Replace LaTeX fragments with links to an image, and produce images.
  17430. When optional argument OVERLAYS is non-nil, display the image on
  17431. top of the fragment instead of replacing it.
  17432. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17433. Some of the options can be changed using the variable
  17434. `org-format-latex-options', which see."
  17435. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17436. (unless (eq processing-type 'verbatim)
  17437. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17438. (cnt 0)
  17439. checkdir-flag)
  17440. (goto-char (point-min))
  17441. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17442. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17443. (overlay-recenter (point-max)))
  17444. (while (re-search-forward math-regexp nil t)
  17445. (unless (and overlays
  17446. (eq (get-char-property (point) 'org-overlay-type)
  17447. 'org-latex-overlay))
  17448. (let* ((context (org-element-context))
  17449. (type (org-element-type context)))
  17450. (when (memq type '(latex-environment latex-fragment))
  17451. (let ((block-type (eq type 'latex-environment))
  17452. (value (org-element-property :value context))
  17453. (beg (org-element-property :begin context))
  17454. (end (save-excursion
  17455. (goto-char (org-element-property :end context))
  17456. (skip-chars-backward " \r\t\n")
  17457. (point))))
  17458. (case processing-type
  17459. (mathjax
  17460. ;; Prepare for MathJax processing.
  17461. (if (eq (char-after beg) ?$)
  17462. (save-excursion
  17463. (delete-region beg end)
  17464. (insert "\\(" (substring value 1 -1) "\\)"))
  17465. (goto-char end)))
  17466. ((dvipng imagemagick)
  17467. ;; Process to an image.
  17468. (incf cnt)
  17469. (goto-char beg)
  17470. (let* ((face (face-at-point))
  17471. ;; Get the colors from the face at point.
  17472. (fg
  17473. (let ((color (plist-get org-format-latex-options
  17474. :foreground)))
  17475. (if (and forbuffer (eq color 'auto))
  17476. (face-attribute face :foreground nil 'default)
  17477. color)))
  17478. (bg
  17479. (let ((color (plist-get org-format-latex-options
  17480. :background)))
  17481. (if (and forbuffer (eq color 'auto))
  17482. (face-attribute face :background nil 'default)
  17483. color)))
  17484. (hash (sha1 (prin1-to-string
  17485. (list org-format-latex-header
  17486. org-latex-default-packages-alist
  17487. org-latex-packages-alist
  17488. org-format-latex-options
  17489. forbuffer value fg bg))))
  17490. (absprefix (expand-file-name prefix dir))
  17491. (linkfile (format "%s_%s.png" prefix hash))
  17492. (movefile (format "%s_%s.png" absprefix hash))
  17493. (sep (and block-type "\n\n"))
  17494. (link (concat sep "[[file:" linkfile "]]" sep))
  17495. (options
  17496. (org-combine-plists
  17497. org-format-latex-options
  17498. `(:foreground ,fg :background ,bg))))
  17499. (when msg (message msg cnt))
  17500. (unless checkdir-flag ; Ensure the directory exists.
  17501. (setq checkdir-flag t)
  17502. (let ((todir (file-name-directory absprefix)))
  17503. (unless (file-directory-p todir)
  17504. (make-directory todir t))))
  17505. (unless (file-exists-p movefile)
  17506. (org-create-formula-image
  17507. value movefile options forbuffer processing-type))
  17508. (if overlays
  17509. (progn
  17510. (dolist (o (overlays-in beg end))
  17511. (when (eq (overlay-get o 'org-overlay-type)
  17512. 'org-latex-overlay)
  17513. (delete-overlay o)))
  17514. (let ((ov (make-overlay beg end)))
  17515. (overlay-put ov
  17516. 'org-overlay-type
  17517. 'org-latex-overlay)
  17518. (overlay-put ov 'evaporate t)
  17519. (if (featurep 'xemacs)
  17520. (progn
  17521. (overlay-put ov 'invisible t)
  17522. (overlay-put
  17523. ov 'end-glyph
  17524. (make-glyph
  17525. (vector 'png :file movefile))))
  17526. (overlay-put
  17527. ov 'display
  17528. (list 'image
  17529. :type 'png
  17530. :file movefile
  17531. :ascent 'center)))
  17532. (push ov org-latex-fragment-image-overlays))
  17533. (goto-char end))
  17534. (delete-region beg end)
  17535. (insert
  17536. (org-add-props link
  17537. (list 'org-latex-src
  17538. (replace-regexp-in-string "\"" "" value)
  17539. 'org-latex-src-embed-type
  17540. (if block-type 'paragraph 'character)))))))
  17541. (mathml
  17542. ;; Process to MathML.
  17543. (unless (org-format-latex-mathml-available-p)
  17544. (user-error "LaTeX to MathML converter not configured"))
  17545. (incf cnt)
  17546. (when msg (message msg cnt))
  17547. (goto-char beg)
  17548. (delete-region beg end)
  17549. (insert (org-format-latex-as-mathml
  17550. value block-type prefix dir)))
  17551. (otherwise
  17552. (error "Unknown conversion type %s for LaTeX fragments"
  17553. processing-type)))))))))))
  17554. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17555. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17556. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17557. sucessful, return the portion between \"<math...> </math>\"
  17558. elements otherwise return nil. When MATHML-FILE is specified,
  17559. write the results in to that file. When invoked as an
  17560. interactive command, prompt for LATEX-FRAG, with initial value
  17561. set to the current active region and echo the results for user
  17562. inspection."
  17563. (interactive (list (let ((frag (when (org-region-active-p)
  17564. (buffer-substring-no-properties
  17565. (region-beginning) (region-end)))))
  17566. (read-string "LaTeX Fragment: " frag nil frag))))
  17567. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17568. (let* ((tmp-in-file
  17569. (let ((file (file-relative-name
  17570. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17571. (write-region latex-frag nil file)
  17572. file))
  17573. (tmp-out-file (file-relative-name
  17574. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17575. (cmd (format-spec
  17576. org-latex-to-mathml-convert-command
  17577. `((?j . ,(and org-latex-to-mathml-jar-file
  17578. (shell-quote-argument
  17579. (expand-file-name
  17580. org-latex-to-mathml-jar-file))))
  17581. (?I . ,(shell-quote-argument tmp-in-file))
  17582. (?i . ,latex-frag)
  17583. (?o . ,(shell-quote-argument tmp-out-file)))))
  17584. mathml shell-command-output)
  17585. (when (org-called-interactively-p 'any)
  17586. (unless (org-format-latex-mathml-available-p)
  17587. (user-error "LaTeX to MathML converter not configured")))
  17588. (message "Running %s" cmd)
  17589. (setq shell-command-output (shell-command-to-string cmd))
  17590. (setq mathml
  17591. (when (file-readable-p tmp-out-file)
  17592. (with-current-buffer (find-file-noselect tmp-out-file t)
  17593. (goto-char (point-min))
  17594. (when (re-search-forward
  17595. (concat
  17596. (regexp-quote
  17597. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17598. "[^>]*?>"
  17599. "\\(.\\|\n\\)*"
  17600. "</math>")
  17601. nil t)
  17602. (prog1 (match-string 0) (kill-buffer))))))
  17603. (cond
  17604. (mathml
  17605. (setq mathml
  17606. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17607. (when mathml-file
  17608. (write-region mathml nil mathml-file))
  17609. (when (org-called-interactively-p 'any)
  17610. (message mathml)))
  17611. ((message "LaTeX to MathML conversion failed")
  17612. (message shell-command-output)))
  17613. (delete-file tmp-in-file)
  17614. (when (file-exists-p tmp-out-file)
  17615. (delete-file tmp-out-file))
  17616. mathml))
  17617. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17618. prefix &optional dir)
  17619. "Use `org-create-math-formula' but check local cache first."
  17620. (let* ((absprefix (expand-file-name prefix dir))
  17621. (print-length nil) (print-level nil)
  17622. (formula-id (concat
  17623. "formula-"
  17624. (sha1
  17625. (prin1-to-string
  17626. (list latex-frag
  17627. org-latex-to-mathml-convert-command)))))
  17628. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17629. (formula-cache-dir (file-name-directory formula-cache)))
  17630. (unless (file-directory-p formula-cache-dir)
  17631. (make-directory formula-cache-dir t))
  17632. (unless (file-exists-p formula-cache)
  17633. (org-create-math-formula latex-frag formula-cache))
  17634. (if (file-exists-p formula-cache)
  17635. ;; Successful conversion. Return the link to MathML file.
  17636. (org-add-props
  17637. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17638. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17639. 'org-latex-src-embed-type (if latex-frag-type
  17640. 'paragraph 'character)))
  17641. ;; Failed conversion. Return the LaTeX fragment verbatim
  17642. latex-frag)))
  17643. (defun org-create-formula-image (string tofile options buffer &optional type)
  17644. "Create an image from LaTeX source using dvipng or convert.
  17645. This function calls either `org-create-formula-image-with-dvipng'
  17646. or `org-create-formula-image-with-imagemagick' depending on the
  17647. value of `org-latex-create-formula-image-program' or on the value
  17648. of the optional TYPE variable.
  17649. Note: ultimately these two function should be combined as they
  17650. share a good deal of logic."
  17651. (org-check-external-command
  17652. "latex" "needed to convert LaTeX fragments to images")
  17653. (funcall
  17654. (case (or type org-latex-create-formula-image-program)
  17655. (dvipng
  17656. (org-check-external-command
  17657. "dvipng" "needed to convert LaTeX fragments to images")
  17658. #'org-create-formula-image-with-dvipng)
  17659. (imagemagick
  17660. (org-check-external-command
  17661. "convert" "you need to install imagemagick")
  17662. #'org-create-formula-image-with-imagemagick)
  17663. (t (error
  17664. "Invalid value of `org-latex-create-formula-image-program'")))
  17665. string tofile options buffer))
  17666. (declare-function org-export-get-backend "ox" (name))
  17667. (declare-function org-export--get-global-options "ox" (&optional backend))
  17668. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17669. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17670. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17671. (defun org-create-formula--latex-header ()
  17672. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17673. (let ((info (org-combine-plists (org-export--get-global-options
  17674. (org-export-get-backend 'latex))
  17675. (org-export--get-inbuffer-options
  17676. (org-export-get-backend 'latex)))))
  17677. (org-latex-guess-babel-language
  17678. (org-latex-guess-inputenc
  17679. (org-splice-latex-header
  17680. org-format-latex-header
  17681. org-latex-default-packages-alist
  17682. org-latex-packages-alist t
  17683. (plist-get info :latex-header)))
  17684. info)))
  17685. (defun org--get-display-dpi ()
  17686. "Get the DPI of the display.
  17687. Assumes that the display has the same pixel width in the
  17688. horizontal and vertical directions."
  17689. (if (display-graphic-p)
  17690. (round (/ (display-pixel-height)
  17691. (/ (display-mm-height) 25.4)))
  17692. (error "Attempt to calculate the dpi of a non-graphic display")))
  17693. ;; This function borrows from Ganesh Swami's latex2png.el
  17694. (defun org-create-formula-image-with-dvipng (string tofile options buffer)
  17695. "This calls dvipng."
  17696. (require 'ox-latex)
  17697. (let* ((tmpdir (if (featurep 'xemacs)
  17698. (temp-directory)
  17699. temporary-file-directory))
  17700. (texfilebase (make-temp-name
  17701. (expand-file-name "orgtex" tmpdir)))
  17702. (texfile (concat texfilebase ".tex"))
  17703. (dvifile (concat texfilebase ".dvi"))
  17704. (pngfile (concat texfilebase ".png"))
  17705. (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
  17706. ;; This assumes that the display has the same pixel width in
  17707. ;; the horizontal and vertical directions
  17708. (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
  17709. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17710. "Black"))
  17711. (bg (or (plist-get options (if buffer :background :html-background))
  17712. "Transparent")))
  17713. (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
  17714. (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
  17715. (if (eq bg 'default) (setq bg (org-dvipng-color :background))
  17716. (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
  17717. (let ((latex-header (org-create-formula--latex-header)))
  17718. (with-temp-file texfile
  17719. (insert latex-header)
  17720. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17721. (let ((dir default-directory))
  17722. (ignore-errors
  17723. (cd tmpdir)
  17724. (call-process "latex" nil nil nil texfile))
  17725. (cd dir))
  17726. (if (not (file-exists-p dvifile))
  17727. (progn (message "Failed to create dvi file from %s" texfile) nil)
  17728. (ignore-errors
  17729. (if (featurep 'xemacs)
  17730. (call-process "dvipng" nil nil nil
  17731. "-fg" fg "-bg" bg
  17732. "-T" "tight"
  17733. "-o" pngfile
  17734. dvifile)
  17735. (call-process "dvipng" nil nil nil
  17736. "-fg" fg "-bg" bg
  17737. "-D" dpi
  17738. ;;"-x" scale "-y" scale
  17739. "-T" "tight"
  17740. "-o" pngfile
  17741. dvifile)))
  17742. (if (not (file-exists-p pngfile))
  17743. (if org-format-latex-signal-error
  17744. (error "Failed to create png file from %s" texfile)
  17745. (message "Failed to create png file from %s" texfile)
  17746. nil)
  17747. ;; Use the requested file name and clean up
  17748. (copy-file pngfile tofile 'replace)
  17749. (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
  17750. (when (file-exists-p (concat texfilebase e))
  17751. (delete-file (concat texfilebase e))))
  17752. pngfile))))
  17753. (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
  17754. (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
  17755. "This calls convert, which is included into imagemagick."
  17756. (require 'ox-latex)
  17757. (let* ((tmpdir (if (featurep 'xemacs)
  17758. (temp-directory)
  17759. temporary-file-directory))
  17760. (texfilebase (make-temp-name
  17761. (expand-file-name "orgtex" tmpdir)))
  17762. (texfile (concat texfilebase ".tex"))
  17763. (pdffile (concat texfilebase ".pdf"))
  17764. (pngfile (concat texfilebase ".png"))
  17765. (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
  17766. (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
  17767. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17768. "black"))
  17769. (bg (or (plist-get options (if buffer :background :html-background))
  17770. "white")))
  17771. (if (eq fg 'default) (setq fg (org-latex-color :foreground))
  17772. (setq fg (org-latex-color-format fg)))
  17773. (if (eq bg 'default) (setq bg (org-latex-color :background))
  17774. (setq bg (org-latex-color-format
  17775. (if (string= bg "Transparent") "white" bg))))
  17776. (let ((latex-header (org-create-formula--latex-header)))
  17777. (with-temp-file texfile
  17778. (insert latex-header)
  17779. (insert "\n\\begin{document}\n"
  17780. "\\definecolor{fg}{rgb}{" fg "}\n"
  17781. "\\definecolor{bg}{rgb}{" bg "}\n"
  17782. "\n\\pagecolor{bg}\n"
  17783. "\n{\\color{fg}\n"
  17784. string
  17785. "\n}\n"
  17786. "\n\\end{document}\n")))
  17787. (org-latex-compile texfile t)
  17788. (if (not (file-exists-p pdffile))
  17789. (progn (message "Failed to create pdf file from %s" texfile) nil)
  17790. (ignore-errors
  17791. (if (featurep 'xemacs)
  17792. (call-process "convert" nil nil nil
  17793. "-density" "96"
  17794. "-trim"
  17795. "-antialias"
  17796. pdffile
  17797. "-quality" "100"
  17798. ;; "-sharpen" "0x1.0"
  17799. pngfile)
  17800. (call-process "convert" nil nil nil
  17801. "-density" dpi
  17802. "-trim"
  17803. "-antialias"
  17804. pdffile
  17805. "-quality" "100"
  17806. ;; "-sharpen" "0x1.0"
  17807. pngfile)))
  17808. (if (not (file-exists-p pngfile))
  17809. (if org-format-latex-signal-error
  17810. (error "Failed to create png file from %s" texfile)
  17811. (message "Failed to create png file from %s" texfile)
  17812. nil)
  17813. ;; Use the requested file name and clean up
  17814. (copy-file pngfile tofile 'replace)
  17815. (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
  17816. (when (file-exists-p (concat texfilebase e))
  17817. (delete-file (concat texfilebase e))))
  17818. pngfile))))
  17819. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17820. "Fill a LaTeX header template TPL.
  17821. In the template, the following place holders will be recognized:
  17822. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17823. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17824. [PACKAGES] \\usepackage statements for PKG
  17825. [NO-PACKAGES] do not include PKG
  17826. [EXTRA] the string EXTRA
  17827. [NO-EXTRA] do not include EXTRA
  17828. For backward compatibility, if both the positive and the negative place
  17829. holder is missing, the positive one (without the \"NO-\") will be
  17830. assumed to be present at the end of the template.
  17831. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17832. EXTRA is a string.
  17833. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17834. (let (rpl (end ""))
  17835. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17836. (setq rpl (if (or (match-end 1) (not def-pkg))
  17837. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17838. tpl (replace-match rpl t t tpl))
  17839. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17840. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17841. (setq rpl (if (or (match-end 1) (not pkg))
  17842. "" (org-latex-packages-to-string pkg snippets-p t))
  17843. tpl (replace-match rpl t t tpl))
  17844. (when pkg (setq end
  17845. (concat end "\n"
  17846. (org-latex-packages-to-string pkg snippets-p)))))
  17847. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17848. (setq rpl (if (or (match-end 1) (not extra))
  17849. "" (concat extra "\n"))
  17850. tpl (replace-match rpl t t tpl))
  17851. (when (and extra (string-match "\\S-" extra))
  17852. (setq end (concat end "\n" extra))))
  17853. (if (string-match "\\S-" end)
  17854. (concat tpl "\n" end)
  17855. tpl)))
  17856. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17857. "Turn an alist of packages into a string with the \\usepackage macros."
  17858. (setq pkg (mapconcat (lambda(p)
  17859. (cond
  17860. ((stringp p) p)
  17861. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17862. (format "%% Package %s omitted" (cadr p)))
  17863. ((equal "" (car p))
  17864. (format "\\usepackage{%s}" (cadr p)))
  17865. (t
  17866. (format "\\usepackage[%s]{%s}"
  17867. (car p) (cadr p)))))
  17868. pkg
  17869. "\n"))
  17870. (if newline (concat pkg "\n") pkg))
  17871. (defun org-dvipng-color (attr)
  17872. "Return a RGB color specification for dvipng."
  17873. (apply 'format "rgb %s %s %s"
  17874. (mapcar 'org-normalize-color
  17875. (if (featurep 'xemacs)
  17876. (color-rgb-components
  17877. (face-property 'default
  17878. (cond ((eq attr :foreground) 'foreground)
  17879. ((eq attr :background) 'background))))
  17880. (color-values (face-attribute 'default attr nil))))))
  17881. (defun org-dvipng-color-format (color-name)
  17882. "Convert COLOR-NAME to a RGB color value for dvipng."
  17883. (apply 'format "rgb %s %s %s"
  17884. (mapcar 'org-normalize-color
  17885. (color-values color-name))))
  17886. (defun org-latex-color (attr)
  17887. "Return a RGB color for the LaTeX color package."
  17888. (apply 'format "%s,%s,%s"
  17889. (mapcar 'org-normalize-color
  17890. (if (featurep 'xemacs)
  17891. (color-rgb-components
  17892. (face-property 'default
  17893. (cond ((eq attr :foreground) 'foreground)
  17894. ((eq attr :background) 'background))))
  17895. (color-values (face-attribute 'default attr nil))))))
  17896. (defun org-latex-color-format (color-name)
  17897. "Convert COLOR-NAME to a RGB color value."
  17898. (apply 'format "%s,%s,%s"
  17899. (mapcar 'org-normalize-color
  17900. (color-values color-name))))
  17901. (defun org-normalize-color (value)
  17902. "Return string to be used as color value for an RGB component."
  17903. (format "%g" (/ value 65535.0)))
  17904. ;; Image display
  17905. (defvar-local org-inline-image-overlays nil)
  17906. (defun org-toggle-inline-images (&optional include-linked)
  17907. "Toggle the display of inline images.
  17908. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17909. (interactive "P")
  17910. (if org-inline-image-overlays
  17911. (progn
  17912. (org-remove-inline-images)
  17913. (when (org-called-interactively-p 'interactive)
  17914. (message "Inline image display turned off")))
  17915. (org-display-inline-images include-linked)
  17916. (when (org-called-interactively-p 'interactive)
  17917. (message (if org-inline-image-overlays
  17918. (format "%d images displayed inline"
  17919. (length org-inline-image-overlays))
  17920. "No images to display inline")))))
  17921. (defun org-redisplay-inline-images ()
  17922. "Refresh the display of inline images."
  17923. (interactive)
  17924. (if (not org-inline-image-overlays)
  17925. (org-toggle-inline-images)
  17926. (org-toggle-inline-images)
  17927. (org-toggle-inline-images)))
  17928. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17929. "Display inline images.
  17930. An inline image is a link which follows either of these
  17931. conventions:
  17932. 1. Its path is a file with an extension matching return value
  17933. from `image-file-name-regexp' and it has no contents.
  17934. 2. Its description consists in a single link of the previous
  17935. type.
  17936. When optional argument INCLUDE-LINKED is non-nil, also links with
  17937. a text description part will be inlined. This can be nice for
  17938. a quick look at those images, but it does not reflect what
  17939. exported files will look like.
  17940. When optional argument REFRESH is non-nil, refresh existing
  17941. images between BEG and END. This will create new image displays
  17942. only if necessary. BEG and END default to the buffer
  17943. boundaries."
  17944. (interactive "P")
  17945. (when (display-graphic-p)
  17946. (unless refresh
  17947. (org-remove-inline-images)
  17948. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17949. (org-with-wide-buffer
  17950. (goto-char (or beg (point-min)))
  17951. (let ((case-fold-search t)
  17952. (file-extension-re (image-file-name-regexp)))
  17953. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17954. (let ((link (save-match-data (org-element-context))))
  17955. ;; Check if we're at an inline image.
  17956. (when (and (equal (org-element-property :type link) "file")
  17957. (or include-linked
  17958. (not (org-element-property :contents-begin link)))
  17959. (let ((parent (org-element-property :parent link)))
  17960. (or (not (eq (org-element-type parent) 'link))
  17961. (not (cdr (org-element-contents parent)))))
  17962. (org-string-match-p file-extension-re
  17963. (org-element-property :path link)))
  17964. (let ((file (expand-file-name
  17965. (org-link-unescape
  17966. (org-element-property :path link)))))
  17967. (when (file-exists-p file)
  17968. (let ((width
  17969. ;; Apply `org-image-actual-width' specifications.
  17970. (cond
  17971. ((not (image-type-available-p 'imagemagick)) nil)
  17972. ((eq org-image-actual-width t) nil)
  17973. ((listp org-image-actual-width)
  17974. (or
  17975. ;; First try to find a width among
  17976. ;; attributes associated to the paragraph
  17977. ;; containing link.
  17978. (let ((paragraph
  17979. (let ((e link))
  17980. (while (and (setq e (org-element-property
  17981. :parent e))
  17982. (not (eq (org-element-type e)
  17983. 'paragraph))))
  17984. e)))
  17985. (when paragraph
  17986. (save-excursion
  17987. (goto-char (org-element-property :begin paragraph))
  17988. (when
  17989. (re-search-forward
  17990. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17991. (org-element-property
  17992. :post-affiliated paragraph)
  17993. t)
  17994. (string-to-number (match-string 1))))))
  17995. ;; Otherwise, fall-back to provided number.
  17996. (car org-image-actual-width)))
  17997. ((numberp org-image-actual-width)
  17998. org-image-actual-width)))
  17999. (old (get-char-property-and-overlay
  18000. (org-element-property :begin link)
  18001. 'org-image-overlay)))
  18002. (if (and (car-safe old) refresh)
  18003. (image-refresh (overlay-get (cdr old) 'display))
  18004. (let ((image (create-image file
  18005. (and width 'imagemagick)
  18006. nil
  18007. :width width)))
  18008. (when image
  18009. (let* ((link
  18010. ;; If inline image is the description
  18011. ;; of another link, be sure to
  18012. ;; consider the latter as the one to
  18013. ;; apply the overlay on.
  18014. (let ((parent
  18015. (org-element-property :parent link)))
  18016. (if (eq (org-element-type parent) 'link)
  18017. parent
  18018. link)))
  18019. (ov (make-overlay
  18020. (org-element-property :begin link)
  18021. (progn
  18022. (goto-char
  18023. (org-element-property :end link))
  18024. (skip-chars-backward " \t")
  18025. (point)))))
  18026. (overlay-put ov 'display image)
  18027. (overlay-put ov 'face 'default)
  18028. (overlay-put ov 'org-image-overlay t)
  18029. (overlay-put
  18030. ov 'modification-hooks
  18031. (list 'org-display-inline-remove-overlay))
  18032. (push ov org-inline-image-overlays)))))))))))))))
  18033. (define-obsolete-function-alias
  18034. 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
  18035. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18036. "Remove inline-display overlay if a corresponding region is modified."
  18037. (let ((inhibit-modification-hooks t))
  18038. (when (and ov after)
  18039. (delete ov org-inline-image-overlays)
  18040. (delete-overlay ov))))
  18041. (defun org-remove-inline-images ()
  18042. "Remove inline display of images."
  18043. (interactive)
  18044. (mapc 'delete-overlay org-inline-image-overlays)
  18045. (setq org-inline-image-overlays nil))
  18046. ;;;; Key bindings
  18047. ;; Outline functions from `outline-mode-prefix-map'
  18048. ;; that can be remapped in Org:
  18049. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18050. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18051. (define-key org-mode-map [remap outline-forward-same-level]
  18052. 'org-forward-heading-same-level)
  18053. (define-key org-mode-map [remap outline-backward-same-level]
  18054. 'org-backward-heading-same-level)
  18055. (define-key org-mode-map [remap outline-show-branches]
  18056. 'org-kill-note-or-show-branches)
  18057. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18058. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18059. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18060. (define-key org-mode-map [remap outline-next-visible-heading]
  18061. 'org-next-visible-heading)
  18062. (define-key org-mode-map [remap outline-previous-visible-heading]
  18063. 'org-previous-visible-heading)
  18064. (define-key org-mode-map [remap show-children] 'org-show-children)
  18065. ;; Outline functions from `outline-mode-prefix-map' that can not
  18066. ;; be remapped in Org:
  18067. ;; - the column "key binding" shows whether the Outline function is still
  18068. ;; available in Org mode on the same key that it has been bound to in
  18069. ;; Outline mode:
  18070. ;; - "overridden": key used for a different functionality in Org mode
  18071. ;; - else: key still bound to the same Outline function in Org mode
  18072. ;; | Outline function | key binding | Org replacement |
  18073. ;; |------------------------------------+-------------+--------------------------|
  18074. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18075. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18076. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18077. ;; | `show-entry' | overridden | no replacement |
  18078. ;; | `show-branches' | `C-c C-k' | still same function |
  18079. ;; | `show-subtree' | overridden | visibility cycling |
  18080. ;; | `show-all' | overridden | no replacement |
  18081. ;; | `hide-subtree' | overridden | visibility cycling |
  18082. ;; | `hide-body' | overridden | no replacement |
  18083. ;; | `hide-entry' | overridden | visibility cycling |
  18084. ;; | `hide-leaves' | overridden | no replacement |
  18085. ;; | `hide-sublevels' | overridden | no replacement |
  18086. ;; | `hide-other' | overridden | no replacement |
  18087. ;; Make `C-c C-x' a prefix key
  18088. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18089. ;; TAB key with modifiers
  18090. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18091. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18092. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18093. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18094. ;; The following line is necessary under Suse GNU/Linux
  18095. (unless (featurep 'xemacs)
  18096. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
  18097. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18098. (define-key org-mode-map [backtab] 'org-shifttab)
  18099. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18100. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18101. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18102. ;; Cursor keys with modifiers
  18103. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18104. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18105. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18106. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18107. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18108. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18109. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18110. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18111. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18112. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18113. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18114. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18115. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18116. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18117. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18118. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18119. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18120. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18121. ;; Babel keys
  18122. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18123. (mapc (lambda (pair)
  18124. (define-key org-babel-map (car pair) (cdr pair)))
  18125. org-babel-key-bindings)
  18126. ;;; Extra keys for tty access.
  18127. ;; We only set them when really needed because otherwise the
  18128. ;; menus don't show the simple keys
  18129. (when (or org-use-extra-keys
  18130. (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
  18131. (not window-system))
  18132. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18133. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18134. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18135. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18136. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18137. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18138. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18139. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18140. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18141. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18142. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18143. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18144. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18145. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18146. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18147. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18148. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18149. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18150. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18151. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18152. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18153. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18154. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18155. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18156. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18157. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18158. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18159. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18160. ;; All the other keys
  18161. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18162. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18163. (if (boundp 'narrow-map)
  18164. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18165. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18166. (if (boundp 'narrow-map)
  18167. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18168. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18169. (if (boundp 'narrow-map)
  18170. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18171. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18172. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18173. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18174. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18175. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18176. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18177. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18178. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18179. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18180. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18181. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18182. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18183. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18184. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18185. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18186. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18187. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18188. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18189. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18190. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18191. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18192. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18193. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18194. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18195. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18196. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18197. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18198. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18199. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18200. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18201. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18202. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18203. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18204. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18205. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18206. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18207. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18208. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18209. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18210. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18211. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18212. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18213. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18214. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18215. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18216. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18217. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18218. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18219. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18220. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18221. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18222. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18223. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18224. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18225. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18226. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18227. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18228. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18229. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18230. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18231. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18232. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18233. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18234. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18235. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18236. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18237. (org-defkey org-mode-map "\C-m" 'org-return)
  18238. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18239. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18240. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18241. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18242. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18243. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18244. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18245. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18246. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18247. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18248. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18249. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18250. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18251. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18252. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18253. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18254. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18255. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18256. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18257. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18258. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18259. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18260. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18261. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18262. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18263. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18264. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18265. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18266. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18267. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18268. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18269. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18270. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18271. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18272. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18273. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18274. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18275. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18276. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18277. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18278. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18279. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18280. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18281. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18282. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18283. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18284. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18285. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18286. (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
  18287. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18288. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18289. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18290. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18291. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18292. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18293. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18294. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18295. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18296. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18297. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18298. (when (featurep 'xemacs)
  18299. (org-defkey org-mode-map 'button3 'popup-mode-menu))
  18300. (defconst org-speed-commands-default
  18301. '(
  18302. ("Outline Navigation")
  18303. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18304. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18305. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18306. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18307. ("F" . org-next-block)
  18308. ("B" . org-previous-block)
  18309. ("u" . (org-speed-move-safe 'outline-up-heading))
  18310. ("j" . org-goto)
  18311. ("g" . (org-refile t))
  18312. ("Outline Visibility")
  18313. ("c" . org-cycle)
  18314. ("C" . org-shifttab)
  18315. (" " . org-display-outline-path)
  18316. ("s" . org-narrow-to-subtree)
  18317. ("=" . org-columns)
  18318. ("Outline Structure Editing")
  18319. ("U" . org-metaup)
  18320. ("D" . org-metadown)
  18321. ("r" . org-metaright)
  18322. ("l" . org-metaleft)
  18323. ("R" . org-shiftmetaright)
  18324. ("L" . org-shiftmetaleft)
  18325. ("i" . (progn (forward-char 1) (call-interactively
  18326. 'org-insert-heading-respect-content)))
  18327. ("^" . org-sort)
  18328. ("w" . org-refile)
  18329. ("a" . org-archive-subtree-default-with-confirmation)
  18330. ("@" . org-mark-subtree)
  18331. ("#" . org-toggle-comment)
  18332. ("Clock Commands")
  18333. ("I" . org-clock-in)
  18334. ("O" . org-clock-out)
  18335. ("Meta Data Editing")
  18336. ("t" . org-todo)
  18337. ("," . (org-priority))
  18338. ("0" . (org-priority ?\ ))
  18339. ("1" . (org-priority ?A))
  18340. ("2" . (org-priority ?B))
  18341. ("3" . (org-priority ?C))
  18342. (":" . org-set-tags-command)
  18343. ("e" . org-set-effort)
  18344. ("E" . org-inc-effort)
  18345. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18346. (org-entry-put (point) "APPT_WARNTIME" m)))
  18347. ("Agenda Views etc")
  18348. ("v" . org-agenda)
  18349. ("/" . org-sparse-tree)
  18350. ("Misc")
  18351. ("o" . org-open-at-point)
  18352. ("?" . org-speed-command-help)
  18353. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18354. (">" . (org-agenda-remove-restriction-lock))
  18355. )
  18356. "The default speed commands.")
  18357. (defun org-print-speed-command (e)
  18358. (if (> (length (car e)) 1)
  18359. (progn
  18360. (princ "\n")
  18361. (princ (car e))
  18362. (princ "\n")
  18363. (princ (make-string (length (car e)) ?-))
  18364. (princ "\n"))
  18365. (princ (car e))
  18366. (princ " ")
  18367. (if (symbolp (cdr e))
  18368. (princ (symbol-name (cdr e)))
  18369. (prin1 (cdr e)))
  18370. (princ "\n")))
  18371. (defun org-speed-command-help ()
  18372. "Show the available speed commands."
  18373. (interactive)
  18374. (if (not org-use-speed-commands)
  18375. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18376. (with-output-to-temp-buffer "*Help*"
  18377. (princ "User-defined Speed commands\n===========================\n")
  18378. (mapc 'org-print-speed-command org-speed-commands-user)
  18379. (princ "\n")
  18380. (princ "Built-in Speed commands\n=======================\n")
  18381. (mapc 'org-print-speed-command org-speed-commands-default))
  18382. (with-current-buffer "*Help*"
  18383. (setq truncate-lines t))))
  18384. (defun org-speed-move-safe (cmd)
  18385. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18386. If not, return to the original position and throw an error."
  18387. (interactive)
  18388. (let ((pos (point)))
  18389. (call-interactively cmd)
  18390. (unless (and (bolp) (org-at-heading-p))
  18391. (goto-char pos)
  18392. (error "Boundary reached while executing %s" cmd))))
  18393. (defvar org-self-insert-command-undo-counter 0)
  18394. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18395. (defvar org-speed-command nil)
  18396. (define-obsolete-function-alias
  18397. 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
  18398. (defun org-speed-command-activate (keys)
  18399. "Hook for activating single-letter speed commands.
  18400. `org-speed-commands-default' specifies a minimal command set.
  18401. Use `org-speed-commands-user' for further customization."
  18402. (when (or (and (bolp) (looking-at org-outline-regexp))
  18403. (and (functionp org-use-speed-commands)
  18404. (funcall org-use-speed-commands)))
  18405. (cdr (assoc keys (append org-speed-commands-user
  18406. org-speed-commands-default)))))
  18407. (define-obsolete-function-alias
  18408. 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
  18409. (defun org-babel-speed-command-activate (keys)
  18410. "Hook for activating single-letter code block commands."
  18411. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18412. (cdr (assoc keys org-babel-key-bindings))))
  18413. (defcustom org-speed-command-hook
  18414. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18415. "Hook for activating speed commands at strategic locations.
  18416. Hook functions are called in sequence until a valid handler is
  18417. found.
  18418. Each hook takes a single argument, a user-pressed command key
  18419. which is also a `self-insert-command' from the global map.
  18420. Within the hook, examine the cursor position and the command key
  18421. and return nil or a valid handler as appropriate. Handler could
  18422. be one of an interactive command, a function, or a form.
  18423. Set `org-use-speed-commands' to non-nil value to enable this
  18424. hook. The default setting is `org-speed-command-activate'."
  18425. :group 'org-structure
  18426. :version "24.1"
  18427. :type 'hook)
  18428. (defun org-self-insert-command (N)
  18429. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18430. If the cursor is in a table looking at whitespace, the whitespace is
  18431. overwritten, and the table is not marked as requiring realignment."
  18432. (interactive "p")
  18433. (org-check-before-invisible-edit 'insert)
  18434. (cond
  18435. ((and org-use-speed-commands
  18436. (let ((kv (this-command-keys-vector)))
  18437. (setq org-speed-command
  18438. (run-hook-with-args-until-success
  18439. 'org-speed-command-hook
  18440. (make-string 1 (aref kv (1- (length kv))))))))
  18441. (cond
  18442. ((commandp org-speed-command)
  18443. (setq this-command org-speed-command)
  18444. (call-interactively org-speed-command))
  18445. ((functionp org-speed-command)
  18446. (funcall org-speed-command))
  18447. ((and org-speed-command (listp org-speed-command))
  18448. (eval org-speed-command))
  18449. (t (let (org-use-speed-commands)
  18450. (call-interactively 'org-self-insert-command)))))
  18451. ((and
  18452. (org-at-table-p)
  18453. (progn
  18454. ;; Check if we blank the field, and if that triggers align.
  18455. (and (featurep 'org-table) org-table-auto-blank-field
  18456. (memq last-command
  18457. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18458. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18459. ;; Got extra space, this field does not determine
  18460. ;; column width.
  18461. (let (org-table-may-need-update) (org-table-blank-field))
  18462. ;; No extra space, this field may determine column
  18463. ;; width.
  18464. (org-table-blank-field)))
  18465. t)
  18466. (eq N 1)
  18467. (looking-at "[^|\n]* \\( \\)|"))
  18468. ;; There is room for insertion without re-aligning the table.
  18469. (delete-region (match-beginning 1) (match-end 1))
  18470. (self-insert-command N))
  18471. (t
  18472. (setq org-table-may-need-update t)
  18473. (self-insert-command N)
  18474. (org-fix-tags-on-the-fly)
  18475. (when org-self-insert-cluster-for-undo
  18476. (if (not (eq last-command 'org-self-insert-command))
  18477. (setq org-self-insert-command-undo-counter 1)
  18478. (if (>= org-self-insert-command-undo-counter 20)
  18479. (setq org-self-insert-command-undo-counter 1)
  18480. (and (> org-self-insert-command-undo-counter 0)
  18481. buffer-undo-list (listp buffer-undo-list)
  18482. (not (cadr buffer-undo-list)) ; remove nil entry
  18483. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18484. (setq org-self-insert-command-undo-counter
  18485. (1+ org-self-insert-command-undo-counter))))))))
  18486. (defun org-check-before-invisible-edit (kind)
  18487. "Check is editing if kind KIND would be dangerous with invisible text around.
  18488. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18489. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18490. (when (and org-catch-invisible-edits
  18491. (or (not (boundp 'visible-mode)) (not visible-mode))
  18492. (or (get-char-property (point) 'invisible)
  18493. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18494. ;; OK, we need to take a closer look
  18495. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18496. (invisible-before-point (unless (bobp) (get-char-property
  18497. (1- (point)) 'invisible)))
  18498. (border-and-ok-direction
  18499. (or
  18500. ;; Check if we are acting predictably before invisible text
  18501. (and invisible-at-point (not invisible-before-point)
  18502. (memq kind '(insert delete-backward)))
  18503. ;; Check if we are acting predictably after invisible text
  18504. ;; This works not well, and I have turned it off. It seems
  18505. ;; better to always show and stop after invisible text.
  18506. ;; (and (not invisible-at-point) invisible-before-point
  18507. ;; (memq kind '(insert delete)))
  18508. )))
  18509. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18510. (memq invisible-before-point '(outline org-hide-block t)))
  18511. (when (eq org-catch-invisible-edits 'error)
  18512. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18513. (if (and org-custom-properties-overlays
  18514. (y-or-n-p "Display invisible properties in this buffer? "))
  18515. (org-toggle-custom-properties-visibility)
  18516. ;; Make the area visible
  18517. (save-excursion
  18518. (when invisible-before-point
  18519. (goto-char (previous-single-char-property-change
  18520. (point) 'invisible)))
  18521. (outline-show-subtree))
  18522. (cond
  18523. ((eq org-catch-invisible-edits 'show)
  18524. ;; That's it, we do the edit after showing
  18525. (message
  18526. "Unfolding invisible region around point before editing")
  18527. (sit-for 1))
  18528. ((and (eq org-catch-invisible-edits 'smart)
  18529. border-and-ok-direction)
  18530. (message "Unfolding invisible region around point before editing"))
  18531. (t
  18532. ;; Don't do the edit, make the user repeat it in full visibility
  18533. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18534. (defun org-fix-tags-on-the-fly ()
  18535. (when (and (equal (char-after (point-at-bol)) ?*)
  18536. (org-at-heading-p))
  18537. (org-align-tags-here org-tags-column)))
  18538. (defun org-delete-backward-char (N)
  18539. "Like `delete-backward-char', insert whitespace at field end in tables.
  18540. When deleting backwards, in tables this function will insert whitespace in
  18541. front of the next \"|\" separator, to keep the table aligned. The table will
  18542. still be marked for re-alignment if the field did fill the entire column,
  18543. because, in this case the deletion might narrow the column."
  18544. (interactive "p")
  18545. (save-match-data
  18546. (org-check-before-invisible-edit 'delete-backward)
  18547. (if (and (org-at-table-p)
  18548. (eq N 1)
  18549. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18550. (looking-at ".*?|"))
  18551. (let ((pos (point))
  18552. (noalign (looking-at "[^|\n\r]* |"))
  18553. (c org-table-may-need-update))
  18554. (backward-delete-char N)
  18555. (unless overwrite-mode
  18556. (skip-chars-forward "^|")
  18557. (insert " ")
  18558. (goto-char (1- pos)))
  18559. ;; noalign: if there were two spaces at the end, this field
  18560. ;; does not determine the width of the column.
  18561. (when noalign (setq org-table-may-need-update c)))
  18562. (backward-delete-char N)
  18563. (org-fix-tags-on-the-fly))))
  18564. (defun org-delete-char (N)
  18565. "Like `delete-char', but insert whitespace at field end in tables.
  18566. When deleting characters, in tables this function will insert whitespace in
  18567. front of the next \"|\" separator, to keep the table aligned. The table will
  18568. still be marked for re-alignment if the field did fill the entire column,
  18569. because, in this case the deletion might narrow the column."
  18570. (interactive "p")
  18571. (save-match-data
  18572. (org-check-before-invisible-edit 'delete)
  18573. (if (and (org-at-table-p)
  18574. (not (bolp))
  18575. (not (= (char-after) ?|))
  18576. (eq N 1))
  18577. (if (looking-at ".*?|")
  18578. (let ((pos (point))
  18579. (noalign (looking-at "[^|\n\r]* |"))
  18580. (c org-table-may-need-update))
  18581. (replace-match
  18582. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18583. (goto-char pos)
  18584. ;; noalign: if there were two spaces at the end, this field
  18585. ;; does not determine the width of the column.
  18586. (when noalign (setq org-table-may-need-update c)))
  18587. (delete-char N))
  18588. (delete-char N)
  18589. (org-fix-tags-on-the-fly))))
  18590. ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
  18591. (put 'org-self-insert-command 'delete-selection
  18592. (lambda ()
  18593. (not (run-hook-with-args-until-success
  18594. 'self-insert-uses-region-functions))))
  18595. (put 'orgtbl-self-insert-command 'delete-selection
  18596. (lambda ()
  18597. (not (run-hook-with-args-until-success
  18598. 'self-insert-uses-region-functions))))
  18599. (put 'org-delete-char 'delete-selection 'supersede)
  18600. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18601. (put 'org-yank 'delete-selection 'yank)
  18602. ;; Make `flyspell-mode' delay after some commands
  18603. (put 'org-self-insert-command 'flyspell-delayed t)
  18604. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18605. (put 'org-delete-char 'flyspell-delayed t)
  18606. (put 'org-delete-backward-char 'flyspell-delayed t)
  18607. ;; Make pabbrev-mode expand after org-mode commands
  18608. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18609. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18610. (defun org-remap (map &rest commands)
  18611. "In MAP, remap the functions given in COMMANDS.
  18612. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18613. (let (new old)
  18614. (while commands
  18615. (setq old (pop commands) new (pop commands))
  18616. (if (fboundp 'command-remapping)
  18617. (org-defkey map (vector 'remap old) new)
  18618. (substitute-key-definition old new map global-map)))))
  18619. (defun org-transpose-words ()
  18620. "Transpose words for Org.
  18621. This uses the `org-mode-transpose-word-syntax-table' syntax
  18622. table, which interprets characters in `org-emphasis-alist' as
  18623. word constituents."
  18624. (interactive)
  18625. (with-syntax-table org-mode-transpose-word-syntax-table
  18626. (call-interactively 'transpose-words)))
  18627. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18628. (when (eq org-enable-table-editor 'optimized)
  18629. ;; If the user wants maximum table support, we need to hijack
  18630. ;; some standard editing functions
  18631. (org-remap org-mode-map
  18632. 'self-insert-command 'org-self-insert-command
  18633. 'delete-char 'org-delete-char
  18634. 'delete-backward-char 'org-delete-backward-char)
  18635. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18636. (defvar org-ctrl-c-ctrl-c-hook nil
  18637. "Hook for functions attaching themselves to `C-c C-c'.
  18638. This can be used to add additional functionality to the C-c C-c
  18639. key which executes context-dependent commands. This hook is run
  18640. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18641. run after the last test.
  18642. Each function will be called with no arguments. The function
  18643. must check if the context is appropriate for it to act. If yes,
  18644. it should do its thing and then return a non-nil value. If the
  18645. context is wrong, just do nothing and return nil.")
  18646. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18647. "Hook for functions attaching themselves to `C-c C-c'.
  18648. This can be used to add additional functionality to the C-c C-c
  18649. key which executes context-dependent commands. This hook is run
  18650. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18651. before the first test.
  18652. Each function will be called with no arguments. The function
  18653. must check if the context is appropriate for it to act. If yes,
  18654. it should do its thing and then return a non-nil value. If the
  18655. context is wrong, just do nothing and return nil.")
  18656. (defvar org-tab-first-hook nil
  18657. "Hook for functions to attach themselves to TAB.
  18658. See `org-ctrl-c-ctrl-c-hook' for more information.
  18659. This hook runs as the first action when TAB is pressed, even before
  18660. `org-cycle' messes around with the `outline-regexp' to cater for
  18661. inline tasks and plain list item folding.
  18662. If any function in this hook returns t, any other actions that
  18663. would have been caused by TAB (such as table field motion or visibility
  18664. cycling) will not occur.")
  18665. (defvar org-tab-after-check-for-table-hook nil
  18666. "Hook for functions to attach themselves to TAB.
  18667. See `org-ctrl-c-ctrl-c-hook' for more information.
  18668. This hook runs after it has been established that the cursor is not in a
  18669. table, but before checking if the cursor is in a headline or if global cycling
  18670. should be done.
  18671. If any function in this hook returns t, not other actions like visibility
  18672. cycling will be done.")
  18673. (defvar org-tab-after-check-for-cycling-hook nil
  18674. "Hook for functions to attach themselves to TAB.
  18675. See `org-ctrl-c-ctrl-c-hook' for more information.
  18676. This hook runs after it has been established that not table field motion and
  18677. not visibility should be done because of current context. This is probably
  18678. the place where a package like yasnippets can hook in.")
  18679. (defvar org-tab-before-tab-emulation-hook nil
  18680. "Hook for functions to attach themselves to TAB.
  18681. See `org-ctrl-c-ctrl-c-hook' for more information.
  18682. This hook runs after every other options for TAB have been exhausted, but
  18683. before indentation and \t insertion takes place.")
  18684. (defvar org-metaleft-hook nil
  18685. "Hook for functions attaching themselves to `M-left'.
  18686. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18687. (defvar org-metaright-hook nil
  18688. "Hook for functions attaching themselves to `M-right'.
  18689. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18690. (defvar org-metaup-hook nil
  18691. "Hook for functions attaching themselves to `M-up'.
  18692. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18693. (defvar org-metadown-hook nil
  18694. "Hook for functions attaching themselves to `M-down'.
  18695. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18696. (defvar org-shiftmetaleft-hook nil
  18697. "Hook for functions attaching themselves to `M-S-left'.
  18698. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18699. (defvar org-shiftmetaright-hook nil
  18700. "Hook for functions attaching themselves to `M-S-right'.
  18701. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18702. (defvar org-shiftmetaup-hook nil
  18703. "Hook for functions attaching themselves to `M-S-up'.
  18704. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18705. (defvar org-shiftmetadown-hook nil
  18706. "Hook for functions attaching themselves to `M-S-down'.
  18707. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18708. (defvar org-metareturn-hook nil
  18709. "Hook for functions attaching themselves to `M-RET'.
  18710. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18711. (defvar org-shiftup-hook nil
  18712. "Hook for functions attaching themselves to `S-up'.
  18713. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18714. (defvar org-shiftup-final-hook nil
  18715. "Hook for functions attaching themselves to `S-up'.
  18716. This one runs after all other options except shift-select have been excluded.
  18717. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18718. (defvar org-shiftdown-hook nil
  18719. "Hook for functions attaching themselves to `S-down'.
  18720. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18721. (defvar org-shiftdown-final-hook nil
  18722. "Hook for functions attaching themselves to `S-down'.
  18723. This one runs after all other options except shift-select have been excluded.
  18724. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18725. (defvar org-shiftleft-hook nil
  18726. "Hook for functions attaching themselves to `S-left'.
  18727. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18728. (defvar org-shiftleft-final-hook nil
  18729. "Hook for functions attaching themselves to `S-left'.
  18730. This one runs after all other options except shift-select have been excluded.
  18731. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18732. (defvar org-shiftright-hook nil
  18733. "Hook for functions attaching themselves to `S-right'.
  18734. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18735. (defvar org-shiftright-final-hook nil
  18736. "Hook for functions attaching themselves to `S-right'.
  18737. This one runs after all other options except shift-select have been excluded.
  18738. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18739. (defun org-modifier-cursor-error ()
  18740. "Throw an error, a modified cursor command was applied in wrong context."
  18741. (user-error "This command is active in special context like tables, headlines or items"))
  18742. (defun org-shiftselect-error ()
  18743. "Throw an error because Shift-Cursor command was applied in wrong context."
  18744. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18745. (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
  18746. (user-error "This command works only in special context like headlines or timestamps")))
  18747. (defun org-call-for-shift-select (cmd)
  18748. (let ((this-command-keys-shift-translated t))
  18749. (call-interactively cmd)))
  18750. (defun org-shifttab (&optional arg)
  18751. "Global visibility cycling or move to previous table field.
  18752. Call `org-table-previous-field' within a table.
  18753. When ARG is nil, cycle globally through visibility states.
  18754. When ARG is a numeric prefix, show contents of this level."
  18755. (interactive "P")
  18756. (cond
  18757. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18758. ((integerp arg)
  18759. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18760. (message "Content view to level: %d" arg)
  18761. (org-content (prefix-numeric-value arg2))
  18762. (org-cycle-show-empty-lines t)
  18763. (setq org-cycle-global-status 'overview)))
  18764. (t (call-interactively 'org-global-cycle))))
  18765. (defun org-shiftmetaleft ()
  18766. "Promote subtree or delete table column.
  18767. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18768. `org-table-delete-column', depending on context. See the
  18769. individual commands for more information."
  18770. (interactive)
  18771. (cond
  18772. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18773. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18774. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18775. ((if (not (org-region-active-p)) (org-at-item-p)
  18776. (save-excursion (goto-char (region-beginning))
  18777. (org-at-item-p)))
  18778. (call-interactively 'org-outdent-item-tree))
  18779. (t (org-modifier-cursor-error))))
  18780. (defun org-shiftmetaright ()
  18781. "Demote subtree or insert table column.
  18782. Calls `org-demote-subtree', `org-indent-item-tree', or
  18783. `org-table-insert-column', depending on context. See the
  18784. individual commands for more information."
  18785. (interactive)
  18786. (cond
  18787. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18788. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18789. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18790. ((if (not (org-region-active-p)) (org-at-item-p)
  18791. (save-excursion (goto-char (region-beginning))
  18792. (org-at-item-p)))
  18793. (call-interactively 'org-indent-item-tree))
  18794. (t (org-modifier-cursor-error))))
  18795. (defun org-shiftmetaup (&optional _arg)
  18796. "Drag the line at point up.
  18797. In a table, kill the current row.
  18798. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18799. but also adjust the previous clocked item in the clock history.
  18800. Everywhere else, drag the line at point up."
  18801. (interactive "P")
  18802. (cond
  18803. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18804. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18805. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18806. (call-interactively 'org-timestamp-up)))
  18807. (t (call-interactively 'org-drag-line-backward))))
  18808. (defun org-shiftmetadown (&optional _arg)
  18809. "Drag the line at point down.
  18810. In a table, insert an empty row at the current line.
  18811. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18812. but also adjust the previous clocked item in the clock history.
  18813. Everywhere else, drag the line at point down."
  18814. (interactive "P")
  18815. (cond
  18816. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18817. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18818. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18819. (call-interactively 'org-timestamp-down)))
  18820. (t (call-interactively 'org-drag-line-forward))))
  18821. (defsubst org-hidden-tree-error ()
  18822. (user-error
  18823. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18824. (defun org-metaleft (&optional _arg)
  18825. "Promote heading, list item at point or move table column left.
  18826. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18827. depending on context. With no specific context, calls the Emacs
  18828. default `backward-word'. See the individual commands for more
  18829. information.
  18830. This function runs the hook `org-metaleft-hook' as a first step,
  18831. and returns at first non-nil value."
  18832. (interactive "P")
  18833. (cond
  18834. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18835. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18836. ((org-with-limited-levels
  18837. (or (org-at-heading-p)
  18838. (and (org-region-active-p)
  18839. (save-excursion
  18840. (goto-char (region-beginning))
  18841. (org-at-heading-p)))))
  18842. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18843. (call-interactively 'org-do-promote))
  18844. ;; At an inline task.
  18845. ((org-at-heading-p)
  18846. (call-interactively 'org-inlinetask-promote))
  18847. ((or (org-at-item-p)
  18848. (and (org-region-active-p)
  18849. (save-excursion
  18850. (goto-char (region-beginning))
  18851. (org-at-item-p))))
  18852. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18853. (call-interactively 'org-outdent-item))
  18854. (t (call-interactively 'backward-word))))
  18855. (defun org-metaright (&optional _arg)
  18856. "Demote heading, list item at point or move table column right.
  18857. In front of a drawer or a block keyword, indent it correctly.
  18858. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18859. `org-indnet-drawer' or `org-indent-block' depending on context.
  18860. With no specific context, calls the Emacs default `forward-word'.
  18861. See the individual commands for more information.
  18862. This function runs the hook `org-metaright-hook' as a first step,
  18863. and returns at first non-nil value."
  18864. (interactive "P")
  18865. (cond
  18866. ((run-hook-with-args-until-success 'org-metaright-hook))
  18867. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18868. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18869. ((org-at-block-p) (call-interactively 'org-indent-block))
  18870. ((org-with-limited-levels
  18871. (or (org-at-heading-p)
  18872. (and (org-region-active-p)
  18873. (save-excursion
  18874. (goto-char (region-beginning))
  18875. (org-at-heading-p)))))
  18876. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18877. (call-interactively 'org-do-demote))
  18878. ;; At an inline task.
  18879. ((org-at-heading-p)
  18880. (call-interactively 'org-inlinetask-demote))
  18881. ((or (org-at-item-p)
  18882. (and (org-region-active-p)
  18883. (save-excursion
  18884. (goto-char (region-beginning))
  18885. (org-at-item-p))))
  18886. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18887. (call-interactively 'org-indent-item))
  18888. (t (call-interactively 'forward-word))))
  18889. (defun org-check-for-hidden (what)
  18890. "Check if there are hidden headlines/items in the current visual line.
  18891. WHAT can be either `headlines' or `items'. If the current line is
  18892. an outline or item heading and it has a folded subtree below it,
  18893. this function returns t, nil otherwise."
  18894. (let ((re (cond
  18895. ((eq what 'headlines) org-outline-regexp-bol)
  18896. ((eq what 'items) (org-item-beginning-re))
  18897. (t (error "This should not happen"))))
  18898. beg end)
  18899. (save-excursion
  18900. (catch 'exit
  18901. (unless (org-region-active-p)
  18902. (setq beg (point-at-bol))
  18903. (beginning-of-line 2)
  18904. (while (and (not (eobp)) ;; this is like `next-line'
  18905. (get-char-property (1- (point)) 'invisible))
  18906. (beginning-of-line 2))
  18907. (setq end (point))
  18908. (goto-char beg)
  18909. (goto-char (point-at-eol))
  18910. (setq end (max end (point)))
  18911. (while (re-search-forward re end t)
  18912. (when (get-char-property (match-beginning 0) 'invisible)
  18913. (throw 'exit t))))
  18914. nil))))
  18915. (defun org-metaup (&optional _arg)
  18916. "Move subtree up or move table row up.
  18917. Calls `org-move-subtree-up' or `org-table-move-row' or
  18918. `org-move-item-up', depending on context. See the individual commands
  18919. for more information."
  18920. (interactive "P")
  18921. (cond
  18922. ((run-hook-with-args-until-success 'org-metaup-hook))
  18923. ((org-region-active-p)
  18924. (let* ((a (min (region-beginning) (region-end)))
  18925. (b (1- (max (region-beginning) (region-end))))
  18926. (c (save-excursion (goto-char a)
  18927. (move-beginning-of-line 0)))
  18928. (d (save-excursion (goto-char a)
  18929. (move-end-of-line 0) (point))))
  18930. (transpose-regions a b c d)
  18931. (goto-char c)))
  18932. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18933. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18934. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18935. (t (org-drag-element-backward))))
  18936. (defun org-metadown (&optional _arg)
  18937. "Move subtree down or move table row down.
  18938. Calls `org-move-subtree-down' or `org-table-move-row' or
  18939. `org-move-item-down', depending on context. See the individual
  18940. commands for more information."
  18941. (interactive "P")
  18942. (cond
  18943. ((run-hook-with-args-until-success 'org-metadown-hook))
  18944. ((org-region-active-p)
  18945. (let* ((a (min (region-beginning) (region-end)))
  18946. (b (max (region-beginning) (region-end)))
  18947. (c (save-excursion (goto-char b)
  18948. (move-beginning-of-line 1)))
  18949. (d (save-excursion (goto-char b)
  18950. (move-end-of-line 1) (1+ (point)))))
  18951. (transpose-regions a b c d)
  18952. (goto-char d)))
  18953. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18954. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18955. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18956. (t (org-drag-element-forward))))
  18957. (defun org-shiftup (&optional arg)
  18958. "Increase item in timestamp or increase priority of current headline.
  18959. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18960. depending on context. See the individual commands for more information."
  18961. (interactive "P")
  18962. (cond
  18963. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18964. ((and org-support-shift-select (org-region-active-p))
  18965. (org-call-for-shift-select 'previous-line))
  18966. ((org-at-timestamp-p t)
  18967. (call-interactively (if org-edit-timestamp-down-means-later
  18968. 'org-timestamp-down 'org-timestamp-up)))
  18969. ((and (not (eq org-support-shift-select 'always))
  18970. org-enable-priority-commands
  18971. (org-at-heading-p))
  18972. (call-interactively 'org-priority-up))
  18973. ((and (not org-support-shift-select) (org-at-item-p))
  18974. (call-interactively 'org-previous-item))
  18975. ((org-clocktable-try-shift 'up arg))
  18976. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18977. (org-support-shift-select
  18978. (org-call-for-shift-select 'previous-line))
  18979. (t (org-shiftselect-error))))
  18980. (defun org-shiftdown (&optional arg)
  18981. "Decrease item in timestamp or decrease priority of current headline.
  18982. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18983. depending on context. See the individual commands for more information."
  18984. (interactive "P")
  18985. (cond
  18986. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18987. ((and org-support-shift-select (org-region-active-p))
  18988. (org-call-for-shift-select 'next-line))
  18989. ((org-at-timestamp-p t)
  18990. (call-interactively (if org-edit-timestamp-down-means-later
  18991. 'org-timestamp-up 'org-timestamp-down)))
  18992. ((and (not (eq org-support-shift-select 'always))
  18993. org-enable-priority-commands
  18994. (org-at-heading-p))
  18995. (call-interactively 'org-priority-down))
  18996. ((and (not org-support-shift-select) (org-at-item-p))
  18997. (call-interactively 'org-next-item))
  18998. ((org-clocktable-try-shift 'down arg))
  18999. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19000. (org-support-shift-select
  19001. (org-call-for-shift-select 'next-line))
  19002. (t (org-shiftselect-error))))
  19003. (defun org-shiftright (&optional arg)
  19004. "Cycle the thing at point or in the current line, depending on context.
  19005. Depending on context, this does one of the following:
  19006. - switch a timestamp at point one day into the future
  19007. - on a headline, switch to the next TODO keyword.
  19008. - on an item, switch entire list to the next bullet type
  19009. - on a property line, switch to the next allowed value
  19010. - on a clocktable definition line, move time block into the future"
  19011. (interactive "P")
  19012. (cond
  19013. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19014. ((and org-support-shift-select (org-region-active-p))
  19015. (org-call-for-shift-select 'forward-char))
  19016. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19017. ((and (not (eq org-support-shift-select 'always))
  19018. (org-at-heading-p))
  19019. (let ((org-inhibit-logging
  19020. (not org-treat-S-cursor-todo-selection-as-state-change))
  19021. (org-inhibit-blocking
  19022. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19023. (org-call-with-arg 'org-todo 'right)))
  19024. ((or (and org-support-shift-select
  19025. (not (eq org-support-shift-select 'always))
  19026. (org-at-item-bullet-p))
  19027. (and (not org-support-shift-select) (org-at-item-p)))
  19028. (org-call-with-arg 'org-cycle-list-bullet nil))
  19029. ((and (not (eq org-support-shift-select 'always))
  19030. (org-at-property-p))
  19031. (call-interactively 'org-property-next-allowed-value))
  19032. ((org-clocktable-try-shift 'right arg))
  19033. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19034. (org-support-shift-select
  19035. (org-call-for-shift-select 'forward-char))
  19036. (t (org-shiftselect-error))))
  19037. (defun org-shiftleft (&optional arg)
  19038. "Cycle the thing at point or in the current line, depending on context.
  19039. Depending on context, this does one of the following:
  19040. - switch a timestamp at point one day into the past
  19041. - on a headline, switch to the previous TODO keyword.
  19042. - on an item, switch entire list to the previous bullet type
  19043. - on a property line, switch to the previous allowed value
  19044. - on a clocktable definition line, move time block into the past"
  19045. (interactive "P")
  19046. (cond
  19047. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19048. ((and org-support-shift-select (org-region-active-p))
  19049. (org-call-for-shift-select 'backward-char))
  19050. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19051. ((and (not (eq org-support-shift-select 'always))
  19052. (org-at-heading-p))
  19053. (let ((org-inhibit-logging
  19054. (not org-treat-S-cursor-todo-selection-as-state-change))
  19055. (org-inhibit-blocking
  19056. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19057. (org-call-with-arg 'org-todo 'left)))
  19058. ((or (and org-support-shift-select
  19059. (not (eq org-support-shift-select 'always))
  19060. (org-at-item-bullet-p))
  19061. (and (not org-support-shift-select) (org-at-item-p)))
  19062. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19063. ((and (not (eq org-support-shift-select 'always))
  19064. (org-at-property-p))
  19065. (call-interactively 'org-property-previous-allowed-value))
  19066. ((org-clocktable-try-shift 'left arg))
  19067. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19068. (org-support-shift-select
  19069. (org-call-for-shift-select 'backward-char))
  19070. (t (org-shiftselect-error))))
  19071. (defun org-shiftcontrolright ()
  19072. "Switch to next TODO set."
  19073. (interactive)
  19074. (cond
  19075. ((and org-support-shift-select (org-region-active-p))
  19076. (org-call-for-shift-select 'forward-word))
  19077. ((and (not (eq org-support-shift-select 'always))
  19078. (org-at-heading-p))
  19079. (org-call-with-arg 'org-todo 'nextset))
  19080. (org-support-shift-select
  19081. (org-call-for-shift-select 'forward-word))
  19082. (t (org-shiftselect-error))))
  19083. (defun org-shiftcontrolleft ()
  19084. "Switch to previous TODO set."
  19085. (interactive)
  19086. (cond
  19087. ((and org-support-shift-select (org-region-active-p))
  19088. (org-call-for-shift-select 'backward-word))
  19089. ((and (not (eq org-support-shift-select 'always))
  19090. (org-at-heading-p))
  19091. (org-call-with-arg 'org-todo 'previousset))
  19092. (org-support-shift-select
  19093. (org-call-for-shift-select 'backward-word))
  19094. (t (org-shiftselect-error))))
  19095. (defun org-shiftcontrolup (&optional n)
  19096. "Change timestamps synchronously up in CLOCK log lines.
  19097. Optional argument N tells to change by that many units."
  19098. (interactive "P")
  19099. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19100. (let (org-support-shift-select)
  19101. (org-clock-timestamps-up n))
  19102. (user-error "Not at a clock log")))
  19103. (defun org-shiftcontroldown (&optional n)
  19104. "Change timestamps synchronously down in CLOCK log lines.
  19105. Optional argument N tells to change by that many units."
  19106. (interactive "P")
  19107. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19108. (let (org-support-shift-select)
  19109. (org-clock-timestamps-down n))
  19110. (user-error "Not at a clock log")))
  19111. (defun org-increase-number-at-point (&optional inc)
  19112. "Increment the number at point.
  19113. With an optional prefix numeric argument INC, increment using
  19114. this numeric value."
  19115. (interactive "p")
  19116. (if (not (number-at-point))
  19117. (user-error "Not on a number")
  19118. (unless inc (setq inc 1))
  19119. (let ((pos (point))
  19120. (beg (skip-chars-backward "-+^/*0-9eE."))
  19121. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19122. (setq nap (buffer-substring-no-properties
  19123. (+ pos beg) (+ pos beg end)))
  19124. (delete-region (+ pos beg) (+ pos beg end))
  19125. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19126. (when (org-at-table-p)
  19127. (org-table-align)
  19128. (org-table-end-of-field 1))))
  19129. (defun org-decrease-number-at-point (&optional inc)
  19130. "Decrement the number at point.
  19131. With an optional prefix numeric argument INC, decrement using
  19132. this numeric value."
  19133. (interactive "p")
  19134. (org-increase-number-at-point (- (or inc 1))))
  19135. (defun org-ctrl-c-ret ()
  19136. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19137. (interactive)
  19138. (cond
  19139. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19140. (t (call-interactively 'org-insert-heading))))
  19141. (defun org-find-visible ()
  19142. (let ((s (point)))
  19143. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19144. (get-char-property s 'invisible)))
  19145. s))
  19146. (defun org-find-invisible ()
  19147. (let ((s (point)))
  19148. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19149. (not (get-char-property s 'invisible))))
  19150. s))
  19151. (defun org-copy-visible (beg end)
  19152. "Copy the visible parts of the region."
  19153. (interactive "r")
  19154. (let (snippets s)
  19155. (save-excursion
  19156. (save-restriction
  19157. (narrow-to-region beg end)
  19158. (setq s (goto-char (point-min)))
  19159. (while (not (= (point) (point-max)))
  19160. (goto-char (org-find-invisible))
  19161. (push (buffer-substring s (point)) snippets)
  19162. (setq s (goto-char (org-find-visible))))))
  19163. (kill-new (apply 'concat (nreverse snippets)))))
  19164. (defun org-copy-special ()
  19165. "Copy region in table or copy current subtree.
  19166. Calls `org-table-copy' or `org-copy-subtree', depending on context.
  19167. See the individual commands for more information."
  19168. (interactive)
  19169. (call-interactively
  19170. (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
  19171. (defun org-cut-special ()
  19172. "Cut region in table or cut current subtree.
  19173. Calls `org-table-copy' or `org-cut-subtree', depending on context.
  19174. See the individual commands for more information."
  19175. (interactive)
  19176. (call-interactively
  19177. (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
  19178. (defun org-paste-special (arg)
  19179. "Paste rectangular region into table, or past subtree relative to level.
  19180. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19181. See the individual commands for more information."
  19182. (interactive "P")
  19183. (if (org-at-table-p)
  19184. (org-table-paste-rectangle)
  19185. (org-paste-subtree arg)))
  19186. (defsubst org-in-fixed-width-region-p ()
  19187. "Is point in a fixed-width region?"
  19188. (save-match-data
  19189. (eq 'fixed-width (org-element-type (org-element-at-point)))))
  19190. (defun org-edit-special (&optional arg)
  19191. "Call a special editor for the element at point.
  19192. When at a table, call the formula editor with `org-table-edit-formulas'.
  19193. When in a source code block, call `org-edit-src-code'.
  19194. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19195. When in an export block, call `org-edit-export-block'.
  19196. When at an #+INCLUDE keyword, visit the included file.
  19197. When at a footnote reference, call `org-edit-footnote-reference'
  19198. On a link, call `ffap' to visit the link at point.
  19199. Otherwise, return a user error."
  19200. (interactive "P")
  19201. (let ((element (org-element-at-point)))
  19202. (assert (not buffer-read-only) nil
  19203. "Buffer is read-only: %s" (buffer-name))
  19204. (pcase (org-element-type element)
  19205. (`src-block
  19206. (if (not arg) (org-edit-src-code)
  19207. (let* ((info (org-babel-get-src-block-info))
  19208. (lang (nth 0 info))
  19209. (params (nth 2 info))
  19210. (session (cdr (assq :session params))))
  19211. (if (not session) (org-edit-src-code)
  19212. ;; At a src-block with a session and function called with
  19213. ;; an ARG: switch to the buffer related to the inferior
  19214. ;; process.
  19215. (switch-to-buffer
  19216. (funcall (intern (concat "org-babel-prep-session:" lang))
  19217. session params))))))
  19218. (`keyword
  19219. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19220. (org-open-link-from-string
  19221. (format "[[%s]]"
  19222. (expand-file-name
  19223. (let ((value (org-element-property :value element)))
  19224. (cond ((not (org-string-nw-p value))
  19225. (user-error "No file to edit"))
  19226. ((string-match "\\`\"\\(.*?\\)\"" value)
  19227. (match-string 1 value))
  19228. ((string-match "\\`[^ \t\"]\\S-*" value)
  19229. (match-string 0 value))
  19230. (t (user-error "No valid file specified")))))))
  19231. (user-error "No special environment to edit here")))
  19232. (`table
  19233. (if (eq (org-element-property :type element) 'table.el)
  19234. (org-edit-table.el)
  19235. (call-interactively 'org-table-edit-formulas)))
  19236. ;; Only Org tables contain `table-row' type elements.
  19237. (`table-row (call-interactively 'org-table-edit-formulas))
  19238. (`example-block (org-edit-src-code))
  19239. (`export-block (org-edit-export-block))
  19240. (`fixed-width (org-edit-fixed-width-region))
  19241. (_
  19242. ;; No notable element at point. Though, we may be at a link or
  19243. ;; a footnote reference, which are objects. Thus, scan deeper.
  19244. (let ((context (org-element-context element)))
  19245. (pcase (org-element-type context)
  19246. (`footnote-reference (org-edit-footnote-reference))
  19247. (`inline-src-block (org-edit-inline-src-code))
  19248. (`link (call-interactively #'ffap))
  19249. (_ (user-error "No special environment to edit here"))))))))
  19250. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19251. (defun org-ctrl-c-ctrl-c (&optional arg)
  19252. "Set tags in headline, or update according to changed information at point.
  19253. This command does many different things, depending on context:
  19254. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19255. this is what we do.
  19256. - If the cursor is on a statistics cookie, update it.
  19257. - If the cursor is in a headline, prompt for tags and insert them
  19258. into the current line, aligned to `org-tags-column'. When called
  19259. with prefix arg, realign all tags in the current buffer.
  19260. - If the cursor is in one of the special #+KEYWORD lines, this
  19261. triggers scanning the buffer for these lines and updating the
  19262. information.
  19263. - If the cursor is inside a table, realign the table. This command
  19264. works even if the automatic table editor has been turned off.
  19265. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19266. the entire table.
  19267. - If the cursor is at a footnote reference or definition, jump to
  19268. the corresponding definition or references, respectively.
  19269. - If the cursor is a the beginning of a dynamic block, update it.
  19270. - If the current buffer is a capture buffer, close note and file it.
  19271. - If the cursor is on a <<<target>>>, update radio targets and
  19272. corresponding links in this buffer.
  19273. - If the cursor is on a numbered item in a plain list, renumber the
  19274. ordered list.
  19275. - If the cursor is on a checkbox, toggle it.
  19276. - If the cursor is on a code block, evaluate it. The variable
  19277. `org-confirm-babel-evaluate' can be used to control prompting
  19278. before code block evaluation, by default every code block
  19279. evaluation requires confirmation. Code block evaluation can be
  19280. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19281. (interactive "P")
  19282. (cond
  19283. ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
  19284. org-occur-highlights)
  19285. (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19286. (org-remove-occur-highlights)
  19287. (message "Temporary highlights/overlays removed from current buffer"))
  19288. ((and (local-variable-p 'org-finish-function (current-buffer))
  19289. (fboundp org-finish-function))
  19290. (funcall org-finish-function))
  19291. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19292. (t
  19293. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  19294. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19295. (user-error "C-c C-c can do nothing useful at this location"))
  19296. (let* ((context (org-element-context))
  19297. (type (org-element-type context)))
  19298. (case type
  19299. ;; When at a link, act according to the parent instead.
  19300. (link (setq context (org-element-property :parent context))
  19301. (setq type (org-element-type context)))
  19302. ;; Unsupported object types: refer to the first supported
  19303. ;; element or object containing it.
  19304. ((bold code entity export-snippet inline-babel-call inline-src-block
  19305. italic latex-fragment line-break macro strike-through subscript
  19306. superscript underline verbatim)
  19307. (setq context
  19308. (org-element-lineage
  19309. context '(radio-target paragraph verse-block table-cell)))))
  19310. ;; For convenience: at the first line of a paragraph on the
  19311. ;; same line as an item, apply function on that item instead.
  19312. (when (eq type 'paragraph)
  19313. (let ((parent (org-element-property :parent context)))
  19314. (when (and (eq (org-element-type parent) 'item)
  19315. (= (line-beginning-position)
  19316. (org-element-property :begin parent)))
  19317. (setq context parent type 'item))))
  19318. ;; Act according to type of element or object at point.
  19319. (case type
  19320. (clock (org-clock-update-time-maybe))
  19321. (dynamic-block
  19322. (save-excursion
  19323. (goto-char (org-element-property :post-affiliated context))
  19324. (org-update-dblock)))
  19325. (footnote-definition
  19326. (goto-char (org-element-property :post-affiliated context))
  19327. (call-interactively 'org-footnote-action))
  19328. (footnote-reference (call-interactively 'org-footnote-action))
  19329. ((headline inlinetask)
  19330. (save-excursion (goto-char (org-element-property :begin context))
  19331. (call-interactively 'org-set-tags)))
  19332. (item
  19333. ;; At an item: a double C-u set checkbox to "[-]"
  19334. ;; unconditionally, whereas a single one will toggle its
  19335. ;; presence. Without a universal argument, if the item
  19336. ;; has a checkbox, toggle it. Otherwise repair the list.
  19337. (let* ((box (org-element-property :checkbox context))
  19338. (struct (org-element-property :structure context))
  19339. (old-struct (copy-tree struct))
  19340. (parents (org-list-parents-alist struct))
  19341. (prevs (org-list-prevs-alist struct))
  19342. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19343. (org-list-set-checkbox
  19344. (org-element-property :begin context) struct
  19345. (cond ((equal arg '(16)) "[-]")
  19346. ((and (not box) (equal arg '(4))) "[ ]")
  19347. ((or (not box) (equal arg '(4))) nil)
  19348. ((eq box 'on) "[ ]")
  19349. (t "[X]")))
  19350. ;; Mimic `org-list-write-struct' but with grabbing
  19351. ;; a return value from `org-list-struct-fix-box'.
  19352. (org-list-struct-fix-ind struct parents 2)
  19353. (org-list-struct-fix-item-end struct)
  19354. (org-list-struct-fix-bul struct prevs)
  19355. (org-list-struct-fix-ind struct parents)
  19356. (let ((block-item
  19357. (org-list-struct-fix-box struct parents prevs orderedp)))
  19358. (if (and box (equal struct old-struct))
  19359. (if (equal arg '(16))
  19360. (message "Checkboxes already reset")
  19361. (user-error "Cannot toggle this checkbox: %s"
  19362. (if (eq box 'on)
  19363. "all subitems checked"
  19364. "unchecked subitems")))
  19365. (org-list-struct-apply-struct struct old-struct)
  19366. (org-update-checkbox-count-maybe))
  19367. (when block-item
  19368. (message "Checkboxes were removed due to empty box at line %d"
  19369. (org-current-line block-item))))))
  19370. (keyword
  19371. (let ((org-inhibit-startup-visibility-stuff t)
  19372. (org-startup-align-all-tables nil))
  19373. (when (boundp 'org-table-coordinate-overlays)
  19374. (mapc 'delete-overlay org-table-coordinate-overlays)
  19375. (setq org-table-coordinate-overlays nil))
  19376. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19377. (message "Local setup has been refreshed"))
  19378. (plain-list
  19379. ;; At a plain list, with a double C-u argument, set
  19380. ;; checkboxes of each item to "[-]", whereas a single one
  19381. ;; will toggle their presence according to the state of the
  19382. ;; first item in the list. Without an argument, repair the
  19383. ;; list.
  19384. (let* ((begin (org-element-property :contents-begin context))
  19385. (beginm (move-marker (make-marker) begin))
  19386. (struct (org-element-property :structure context))
  19387. (old-struct (copy-tree struct))
  19388. (first-box (save-excursion
  19389. (goto-char begin)
  19390. (looking-at org-list-full-item-re)
  19391. (match-string-no-properties 3)))
  19392. (new-box (cond ((equal arg '(16)) "[-]")
  19393. ((equal arg '(4)) (unless first-box "[ ]"))
  19394. ((equal first-box "[X]") "[ ]")
  19395. (t "[X]"))))
  19396. (cond
  19397. (arg
  19398. (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
  19399. (org-list-get-all-items
  19400. begin struct (org-list-prevs-alist struct))))
  19401. ((and first-box (eq (point) begin))
  19402. ;; For convenience, when point is at bol on the first
  19403. ;; item of the list and no argument is provided, simply
  19404. ;; toggle checkbox of that item, if any.
  19405. (org-list-set-checkbox begin struct new-box)))
  19406. (org-list-write-struct
  19407. struct (org-list-parents-alist struct) old-struct)
  19408. (org-update-checkbox-count-maybe)
  19409. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19410. ((property-drawer node-property)
  19411. (call-interactively 'org-property-action))
  19412. ((radio-target target)
  19413. (call-interactively 'org-update-radio-target-regexp))
  19414. (statistics-cookie
  19415. (call-interactively 'org-update-statistics-cookies))
  19416. ((table table-cell table-row)
  19417. ;; At a table, recalculate every field and align it. Also
  19418. ;; send the table if necessary. If the table has
  19419. ;; a `table.el' type, just give up. At a table row or
  19420. ;; cell, maybe recalculate line but always align table.
  19421. (if (eq (org-element-property :type context) 'table.el)
  19422. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19423. Use \\[org-edit-special] to edit table.el tables"))
  19424. (let ((org-enable-table-editor t))
  19425. (if (or (eq type 'table)
  19426. ;; Check if point is at a TBLFM line.
  19427. (and (eq type 'table-row)
  19428. (= (point) (org-element-property :end context))))
  19429. (save-excursion
  19430. (if (org-at-TBLFM-p)
  19431. (progn (require 'org-table)
  19432. (org-table-calc-current-TBLFM))
  19433. (goto-char (org-element-property :contents-begin context))
  19434. (org-call-with-arg 'org-table-recalculate (or arg t))
  19435. (orgtbl-send-table 'maybe)))
  19436. (org-table-maybe-eval-formula)
  19437. (cond (arg (call-interactively 'org-table-recalculate))
  19438. ((org-table-maybe-recalculate-line))
  19439. (t (org-table-align)))))))
  19440. (timestamp (org-timestamp-change 0 'day))
  19441. (otherwise
  19442. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19443. (user-error
  19444. "C-c C-c can do nothing useful at this location")))))))))
  19445. (defun org-mode-restart ()
  19446. (interactive)
  19447. (let ((indent-status (org-bound-and-true-p org-indent-mode)))
  19448. (funcall major-mode)
  19449. (hack-local-variables)
  19450. (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
  19451. (org-indent-mode -1)))
  19452. (message "%s restarted" major-mode))
  19453. (defun org-kill-note-or-show-branches ()
  19454. "If this is a Note buffer, abort storing the note. Else call `show-branches'."
  19455. (interactive)
  19456. (if (not org-finish-function)
  19457. (progn
  19458. (outline-hide-subtree)
  19459. (call-interactively 'outline-show-branches))
  19460. (let ((org-note-abort t))
  19461. (funcall org-finish-function))))
  19462. (defun org-delete-indentation (&optional ARG)
  19463. "Join current line to previous and fix whitespace at join.
  19464. If previous line is a headline add to headline title. Otherwise
  19465. the function calls `delete-indentation'.
  19466. With argument, join this line to following line."
  19467. (interactive "*P")
  19468. (if (save-excursion
  19469. (if ARG (beginning-of-line)
  19470. (forward-line -1))
  19471. (looking-at org-complex-heading-regexp))
  19472. ;; At headline.
  19473. (let ((tags-column (when (match-beginning 5)
  19474. (save-excursion (goto-char (match-beginning 5))
  19475. (current-column))))
  19476. (string (concat " " (progn (when ARG (forward-line 1))
  19477. (org-trim (delete-and-extract-region
  19478. (line-beginning-position)
  19479. (line-end-position)))))))
  19480. (unless (bobp) (delete-region (point) (1- (point))))
  19481. (goto-char (or (match-end 4)
  19482. (match-beginning 5)
  19483. (match-end 0)))
  19484. (skip-chars-backward " \t")
  19485. (save-excursion (insert string))
  19486. ;; Adjust alignment of tags.
  19487. (when tags-column
  19488. (org-align-tags-here (if org-auto-align-tags
  19489. org-tags-column
  19490. tags-column))))
  19491. (delete-indentation ARG)))
  19492. (defun org-open-line (n)
  19493. "Insert a new row in tables, call `open-line' elsewhere.
  19494. If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
  19495. (interactive "*p")
  19496. (cond
  19497. ((not org-special-ctrl-o)
  19498. (open-line n))
  19499. ((org-at-table-p)
  19500. (org-table-insert-row))
  19501. (t
  19502. (open-line n))))
  19503. (defun org-return (&optional indent)
  19504. "Goto next table row or insert a newline.
  19505. Calls `org-table-next-row' or `newline', depending on context.
  19506. When optional INDENT argument is non-nil, call
  19507. `newline-and-indent' instead of `newline'.
  19508. When `org-return-follows-link' is non-nil and point is on
  19509. a timestamp or a link, call `org-open-at-point'. However, it
  19510. will not happen if point is in a table or on a \"dead\"
  19511. object (e.g., within a comment). In these case, you need to use
  19512. `org-open-at-point' directly."
  19513. (interactive)
  19514. (let ((context (if org-return-follows-link (org-element-context)
  19515. (org-element-at-point))))
  19516. (cond
  19517. ;; In a table, call `org-table-next-row'.
  19518. ((or (and (eq (org-element-type context) 'table)
  19519. (>= (point) (org-element-property :contents-begin context))
  19520. (< (point) (org-element-property :contents-end context)))
  19521. (org-element-lineage context '(table-row table-cell) t))
  19522. (org-table-justify-field-maybe)
  19523. (call-interactively #'org-table-next-row))
  19524. ;; On a link or a timestamp, call `org-open-at-point' if
  19525. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19526. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19527. ((and org-return-follows-link
  19528. (or (org-in-regexp org-ts-regexp-both nil t)
  19529. (org-in-regexp org-tsr-regexp-both nil t)
  19530. (org-in-regexp org-any-link-re nil t)))
  19531. (call-interactively #'org-open-at-point))
  19532. ;; Insert newline in heading, but preserve tags.
  19533. ((and (not (bolp))
  19534. (save-excursion (beginning-of-line)
  19535. (looking-at org-complex-heading-regexp)))
  19536. ;; At headline. Split line. However, if point is on keyword,
  19537. ;; priority cookie or tags, do not break any of them: add
  19538. ;; a newline after the headline instead.
  19539. (let ((tags-column (and (match-beginning 5)
  19540. (save-excursion (goto-char (match-beginning 5))
  19541. (current-column))))
  19542. (string
  19543. (when (and (match-end 4)
  19544. (>= (point)
  19545. (or (match-end 3) (match-end 2) (1+ (match-end 1))))
  19546. (<= (point) (match-end 4)))
  19547. (delete-and-extract-region (point) (match-end 4)))))
  19548. (when (and tags-column string) ; Adjust tag alignment.
  19549. (org-align-tags-here
  19550. (if org-auto-align-tags org-tags-column tags-column)))
  19551. (end-of-line)
  19552. (org-show-entry)
  19553. (if indent (newline-and-indent) (newline))
  19554. (when string (save-excursion (insert (org-trim string))))))
  19555. ;; In a list, make sure indenting keeps trailing text within.
  19556. ((and indent
  19557. (not (eolp))
  19558. (org-element-lineage context '(item)))
  19559. (let ((trailing-data
  19560. (delete-and-extract-region (point) (line-end-position))))
  19561. (newline-and-indent)
  19562. (save-excursion (insert trailing-data))))
  19563. (t (if indent (newline-and-indent) (newline))))))
  19564. (defun org-return-indent ()
  19565. "Goto next table row or insert a newline and indent.
  19566. Calls `org-table-next-row' or `newline-and-indent', depending on
  19567. context. See the individual commands for more information."
  19568. (interactive)
  19569. (org-return t))
  19570. (defun org-ctrl-c-star ()
  19571. "Compute table, or change heading status of lines.
  19572. Calls `org-table-recalculate' or `org-toggle-heading',
  19573. depending on context."
  19574. (interactive)
  19575. (cond
  19576. ((org-at-table-p)
  19577. (call-interactively 'org-table-recalculate))
  19578. (t
  19579. ;; Convert all lines in region to list items
  19580. (call-interactively 'org-toggle-heading))))
  19581. (defun org-ctrl-c-minus ()
  19582. "Insert separator line in table or modify bullet status of line.
  19583. Also turns a plain line or a region of lines into list items.
  19584. Calls `org-table-insert-hline', `org-toggle-item', or
  19585. `org-cycle-list-bullet', depending on context."
  19586. (interactive)
  19587. (cond
  19588. ((org-at-table-p)
  19589. (call-interactively 'org-table-insert-hline))
  19590. ((org-region-active-p)
  19591. (call-interactively 'org-toggle-item))
  19592. ((org-in-item-p)
  19593. (call-interactively 'org-cycle-list-bullet))
  19594. (t
  19595. (call-interactively 'org-toggle-item))))
  19596. (defun org-toggle-item (arg)
  19597. "Convert headings or normal lines to items, items to normal lines.
  19598. If there is no active region, only the current line is considered.
  19599. If the first non blank line in the region is a headline, convert
  19600. all headlines to items, shifting text accordingly.
  19601. If it is an item, convert all items to normal lines.
  19602. If it is normal text, change region into a list of items.
  19603. With a prefix argument ARG, change the region in a single item."
  19604. (interactive "P")
  19605. (let ((shift-text
  19606. (function
  19607. ;; Shift text in current section to IND, from point to END.
  19608. ;; The function leaves point to END line.
  19609. (lambda (ind end)
  19610. (let ((min-i 1000) (end (copy-marker end)))
  19611. ;; First determine the minimum indentation (MIN-I) of
  19612. ;; the text.
  19613. (save-excursion
  19614. (catch 'exit
  19615. (while (< (point) end)
  19616. (let ((i (org-get-indentation)))
  19617. (cond
  19618. ;; Skip blank lines and inline tasks.
  19619. ((looking-at "^[ \t]*$"))
  19620. ((looking-at org-outline-regexp-bol))
  19621. ;; We can't find less than 0 indentation.
  19622. ((zerop i) (throw 'exit (setq min-i 0)))
  19623. ((< i min-i) (setq min-i i))))
  19624. (forward-line))))
  19625. ;; Then indent each line so that a line indented to
  19626. ;; MIN-I becomes indented to IND. Ignore blank lines
  19627. ;; and inline tasks in the process.
  19628. (let ((delta (- ind min-i)))
  19629. (while (< (point) end)
  19630. (unless (or (looking-at "^[ \t]*$")
  19631. (looking-at org-outline-regexp-bol))
  19632. (org-indent-line-to (+ (org-get-indentation) delta)))
  19633. (forward-line)))))))
  19634. (skip-blanks
  19635. (function
  19636. ;; Return beginning of first non-blank line, starting from
  19637. ;; line at POS.
  19638. (lambda (pos)
  19639. (save-excursion
  19640. (goto-char pos)
  19641. (skip-chars-forward " \r\t\n")
  19642. (point-at-bol)))))
  19643. beg end)
  19644. ;; Determine boundaries of changes.
  19645. (if (org-region-active-p)
  19646. (setq beg (funcall skip-blanks (region-beginning))
  19647. end (copy-marker (region-end)))
  19648. (setq beg (funcall skip-blanks (point-at-bol))
  19649. end (copy-marker (point-at-eol))))
  19650. ;; Depending on the starting line, choose an action on the text
  19651. ;; between BEG and END.
  19652. (org-with-limited-levels
  19653. (save-excursion
  19654. (goto-char beg)
  19655. (cond
  19656. ;; Case 1. Start at an item: de-itemize. Note that it only
  19657. ;; happens when a region is active: `org-ctrl-c-minus'
  19658. ;; would call `org-cycle-list-bullet' otherwise.
  19659. ((org-at-item-p)
  19660. (while (< (point) end)
  19661. (when (org-at-item-p)
  19662. (skip-chars-forward " \t")
  19663. (delete-region (point) (match-end 0)))
  19664. (forward-line)))
  19665. ;; Case 2. Start at an heading: convert to items.
  19666. ((org-at-heading-p)
  19667. (let* ((bul (org-list-bullet-string "-"))
  19668. (bul-len (length bul))
  19669. (done (org-entry-is-done-p))
  19670. (todo (org-entry-is-todo-p))
  19671. ;; Indentation of the first heading. It should be
  19672. ;; relative to the indentation of its parent, if any.
  19673. (start-ind (save-excursion
  19674. (cond
  19675. ((not org-adapt-indentation) 0)
  19676. ((not (outline-previous-heading)) 0)
  19677. (t (length (match-string 0))))))
  19678. ;; Level of first heading. Further headings will be
  19679. ;; compared to it to determine hierarchy in the list.
  19680. (ref-level (org-reduced-level (org-outline-level))))
  19681. (when (or done todo) (org-todo ""))
  19682. (while (< (point) end)
  19683. (let* ((level (org-reduced-level (org-outline-level)))
  19684. (delta (max 0 (- level ref-level))))
  19685. ;; If current headline is less indented than the first
  19686. ;; one, set it as reference, in order to preserve
  19687. ;; subtrees.
  19688. (when (< level ref-level) (setq ref-level level))
  19689. (replace-match bul t t)
  19690. (org-indent-line-to (+ start-ind (* delta bul-len)))
  19691. (when (or done todo)
  19692. (let* ((struct (org-list-struct))
  19693. (old (copy-tree struct)))
  19694. (org-list-set-checkbox (line-beginning-position)
  19695. struct
  19696. (if done "[X]" "[ ]"))
  19697. (org-list-write-struct struct
  19698. (org-list-parents-alist struct)
  19699. old)))
  19700. ;; Ensure all text down to END (or SECTION-END) belongs
  19701. ;; to the newly created item.
  19702. (let ((section-end (save-excursion
  19703. (or (outline-next-heading) (point)))))
  19704. (forward-line)
  19705. (funcall shift-text
  19706. (+ start-ind (* (1+ delta) bul-len))
  19707. (min end section-end)))))))
  19708. ;; Case 3. Normal line with ARG: make the first line of region
  19709. ;; an item, and shift indentation of others lines to
  19710. ;; set them as item's body.
  19711. (arg (let* ((bul (org-list-bullet-string "-"))
  19712. (bul-len (length bul))
  19713. (ref-ind (org-get-indentation)))
  19714. (skip-chars-forward " \t")
  19715. (insert bul)
  19716. (forward-line)
  19717. (while (< (point) end)
  19718. ;; Ensure that lines less indented than first one
  19719. ;; still get included in item body.
  19720. (funcall shift-text
  19721. (+ ref-ind bul-len)
  19722. (min end (save-excursion (or (outline-next-heading)
  19723. (point)))))
  19724. (forward-line))))
  19725. ;; Case 4. Normal line without ARG: turn each non-item line
  19726. ;; into an item.
  19727. (t
  19728. (while (< (point) end)
  19729. (unless (or (org-at-heading-p) (org-at-item-p))
  19730. (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
  19731. (replace-match
  19732. (concat "\\1" (org-list-bullet-string "-") "\\2"))))
  19733. (forward-line))))))))
  19734. (defun org-toggle-heading (&optional nstars)
  19735. "Convert headings to normal text, or items or text to headings.
  19736. If there is no active region, only convert the current line.
  19737. With a \\[universal-argument] prefix, convert the whole list at
  19738. point into heading.
  19739. In a region:
  19740. - If the first non blank line is a headline, remove the stars
  19741. from all headlines in the region.
  19742. - If it is a normal line, turn each and every normal line (i.e.,
  19743. not an heading or an item) in the region into headings. If you
  19744. want to convert only the first line of this region, use one
  19745. universal prefix argument.
  19746. - If it is a plain list item, turn all plain list items into headings.
  19747. When converting a line into a heading, the number of stars is chosen
  19748. such that the lines become children of the current entry. However,
  19749. when a numeric prefix argument is given, its value determines the
  19750. number of stars to add."
  19751. (interactive "P")
  19752. (let ((skip-blanks
  19753. (function
  19754. ;; Return beginning of first non-blank line, starting from
  19755. ;; line at POS.
  19756. (lambda (pos)
  19757. (save-excursion
  19758. (goto-char pos)
  19759. (while (org-at-comment-p) (forward-line))
  19760. (skip-chars-forward " \r\t\n")
  19761. (point-at-bol)))))
  19762. beg end toggled)
  19763. ;; Determine boundaries of changes. If a universal prefix has
  19764. ;; been given, put the list in a region. If region ends at a bol,
  19765. ;; do not consider the last line to be in the region.
  19766. (when (and current-prefix-arg (org-at-item-p))
  19767. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19768. (org-mark-element))
  19769. (if (org-region-active-p)
  19770. (setq beg (funcall skip-blanks (region-beginning))
  19771. end (copy-marker (save-excursion
  19772. (goto-char (region-end))
  19773. (if (bolp) (point) (point-at-eol)))))
  19774. (setq beg (funcall skip-blanks (point-at-bol))
  19775. end (copy-marker (point-at-eol))))
  19776. ;; Ensure inline tasks don't count as headings.
  19777. (org-with-limited-levels
  19778. (save-excursion
  19779. (goto-char beg)
  19780. (cond
  19781. ;; Case 1. Started at an heading: de-star headings.
  19782. ((org-at-heading-p)
  19783. (while (< (point) end)
  19784. (when (org-at-heading-p t)
  19785. (looking-at org-outline-regexp) (replace-match "")
  19786. (setq toggled t))
  19787. (forward-line)))
  19788. ;; Case 2. Started at an item: change items into headlines.
  19789. ;; One star will be added by `org-list-to-subtree'.
  19790. ((org-at-item-p)
  19791. (while (< (point) end)
  19792. (when (org-at-item-p)
  19793. ;; Pay attention to cases when region ends before list.
  19794. (let* ((struct (org-list-struct))
  19795. (list-end
  19796. (min (org-list-get-bottom-point struct) (1+ end))))
  19797. (save-restriction
  19798. (narrow-to-region (point) list-end)
  19799. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19800. (setq toggled t))
  19801. (forward-line)))
  19802. ;; Case 3. Started at normal text: make every line an heading,
  19803. ;; skipping headlines and items.
  19804. (t (let* ((stars
  19805. (make-string
  19806. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19807. (add-stars
  19808. (cond (nstars "") ; stars from prefix only
  19809. ((equal stars "") "*") ; before first heading
  19810. (org-odd-levels-only "**") ; inside heading, odd
  19811. (t "*"))) ; inside heading, oddeven
  19812. (rpl (concat stars add-stars " "))
  19813. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19814. (while (< (point) (if (equal nstars '(4)) lend end))
  19815. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19816. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19817. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19818. (forward-line)))))))
  19819. (unless toggled (message "Cannot toggle heading from here"))))
  19820. (defun org-meta-return (&optional _arg)
  19821. "Insert a new heading or wrap a region in a table.
  19822. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19823. on context. See the individual commands for more information."
  19824. (interactive)
  19825. (org-check-before-invisible-edit 'insert)
  19826. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19827. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19828. #'org-insert-heading))))
  19829. ;;; Menu entries
  19830. (defsubst org-in-subtree-not-table-p ()
  19831. "Are we in a subtree and not in a table?"
  19832. (and (not (org-before-first-heading-p))
  19833. (not (org-at-table-p))))
  19834. ;; Define the Org-mode menus
  19835. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19836. '("Tbl"
  19837. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19838. ["Next Field" org-cycle (org-at-table-p)]
  19839. ["Previous Field" org-shifttab (org-at-table-p)]
  19840. ["Next Row" org-return (org-at-table-p)]
  19841. "--"
  19842. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19843. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19844. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19845. "--"
  19846. ("Column"
  19847. ["Move Column Left" org-metaleft (org-at-table-p)]
  19848. ["Move Column Right" org-metaright (org-at-table-p)]
  19849. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19850. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19851. ("Row"
  19852. ["Move Row Up" org-metaup (org-at-table-p)]
  19853. ["Move Row Down" org-metadown (org-at-table-p)]
  19854. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19855. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19856. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19857. "--"
  19858. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19859. ("Rectangle"
  19860. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19861. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19862. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19863. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19864. "--"
  19865. ("Calculate"
  19866. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19867. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19868. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19869. "--"
  19870. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19871. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19872. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19873. "--"
  19874. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19875. "--"
  19876. ["Sum Column/Rectangle" org-table-sum
  19877. (or (org-at-table-p) (org-region-active-p))]
  19878. ["Which Column?" org-table-current-column (org-at-table-p)])
  19879. ["Debug Formulas"
  19880. org-table-toggle-formula-debugger
  19881. :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
  19882. ["Show Col/Row Numbers"
  19883. org-table-toggle-coordinate-overlays
  19884. :style toggle
  19885. :selected (org-bound-and-true-p org-table-overlay-coordinates)]
  19886. "--"
  19887. ["Create" org-table-create (and (not (org-at-table-p))
  19888. org-enable-table-editor)]
  19889. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19890. ["Import from File" org-table-import (not (org-at-table-p))]
  19891. ["Export to File" org-table-export (org-at-table-p)]
  19892. "--"
  19893. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19894. "--"
  19895. ("Plot"
  19896. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19897. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19898. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19899. '("Org"
  19900. ("Show/Hide"
  19901. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19902. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19903. ["Sparse Tree..." org-sparse-tree t]
  19904. ["Reveal Context" org-reveal t]
  19905. ["Show All" outline-show-all t]
  19906. "--"
  19907. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19908. "--"
  19909. ["New Heading" org-insert-heading t]
  19910. ("Navigate Headings"
  19911. ["Up" outline-up-heading t]
  19912. ["Next" outline-next-visible-heading t]
  19913. ["Previous" outline-previous-visible-heading t]
  19914. ["Next Same Level" outline-forward-same-level t]
  19915. ["Previous Same Level" outline-backward-same-level t]
  19916. "--"
  19917. ["Jump" org-goto t])
  19918. ("Edit Structure"
  19919. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19920. "--"
  19921. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19922. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19923. "--"
  19924. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19925. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19926. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19927. "--"
  19928. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19929. "--"
  19930. ["Copy visible text" org-copy-visible t]
  19931. "--"
  19932. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19933. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19934. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19935. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19936. "--"
  19937. ["Sort Region/Children" org-sort t]
  19938. "--"
  19939. ["Convert to odd levels" org-convert-to-odd-levels t]
  19940. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19941. ("Editing"
  19942. ["Emphasis..." org-emphasize t]
  19943. ["Edit Source Example" org-edit-special t]
  19944. "--"
  19945. ["Footnote new/jump" org-footnote-action t]
  19946. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19947. ("Archive"
  19948. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19949. "--"
  19950. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19951. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19952. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19953. )
  19954. "--"
  19955. ("Hyperlinks"
  19956. ["Store Link (Global)" org-store-link t]
  19957. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19958. ["Insert Link" org-insert-link t]
  19959. ["Follow Link" org-open-at-point t]
  19960. "--"
  19961. ["Next link" org-next-link t]
  19962. ["Previous link" org-previous-link t]
  19963. "--"
  19964. ["Descriptive Links"
  19965. org-toggle-link-display
  19966. :style radio
  19967. :selected org-descriptive-links
  19968. ]
  19969. ["Literal Links"
  19970. org-toggle-link-display
  19971. :style radio
  19972. :selected (not org-descriptive-links)])
  19973. "--"
  19974. ("TODO Lists"
  19975. ["TODO/DONE/-" org-todo t]
  19976. ("Select keyword"
  19977. ["Next keyword" org-shiftright (org-at-heading-p)]
  19978. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19979. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19980. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19981. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19982. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19983. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19984. "--"
  19985. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19986. :selected org-enforce-todo-dependencies :style toggle :active t]
  19987. "Settings for tree at point"
  19988. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19989. :selected (org-entry-get nil "ORDERED")
  19990. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19991. ["Do Children parallel" org-toggle-ordered-property :style radio
  19992. :selected (not (org-entry-get nil "ORDERED"))
  19993. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19994. "--"
  19995. ["Set Priority" org-priority t]
  19996. ["Priority Up" org-shiftup t]
  19997. ["Priority Down" org-shiftdown t]
  19998. "--"
  19999. ["Get news from all feeds" org-feed-update-all t]
  20000. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  20001. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  20002. ("TAGS and Properties"
  20003. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  20004. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  20005. "--"
  20006. ["Set property" org-set-property (not (org-before-first-heading-p))]
  20007. ["Column view of properties" org-columns t]
  20008. ["Insert Column View DBlock" org-insert-columns-dblock t])
  20009. ("Dates and Scheduling"
  20010. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  20011. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  20012. ("Change Date"
  20013. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  20014. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  20015. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  20016. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  20017. ["Compute Time Range" org-evaluate-time-range t]
  20018. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  20019. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  20020. "--"
  20021. ["Custom time format" org-toggle-time-stamp-overlays
  20022. :style radio :selected org-display-custom-times]
  20023. "--"
  20024. ["Goto Calendar" org-goto-calendar t]
  20025. ["Date from Calendar" org-date-from-calendar t]
  20026. "--"
  20027. ["Start/Restart Timer" org-timer-start t]
  20028. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  20029. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  20030. ["Insert Timer String" org-timer t]
  20031. ["Insert Timer Item" org-timer-item t])
  20032. ("Logging work"
  20033. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  20034. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  20035. ["Clock out" org-clock-out t]
  20036. ["Clock cancel" org-clock-cancel t]
  20037. "--"
  20038. ["Mark as default task" org-clock-mark-default-task t]
  20039. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  20040. ["Goto running clock" org-clock-goto t]
  20041. "--"
  20042. ["Display times" org-clock-display t]
  20043. ["Create clock table" org-clock-report t]
  20044. "--"
  20045. ["Record DONE time"
  20046. (progn (setq org-log-done (not org-log-done))
  20047. (message "Switching to %s will %s record a timestamp"
  20048. (car org-done-keywords)
  20049. (if org-log-done "automatically" "not")))
  20050. :style toggle :selected org-log-done])
  20051. "--"
  20052. ["Agenda Command..." org-agenda t]
  20053. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  20054. ("File List for Agenda")
  20055. ("Special views current file"
  20056. ["TODO Tree" org-show-todo-tree t]
  20057. ["Check Deadlines" org-check-deadlines t]
  20058. ["Timeline" org-timeline t]
  20059. ["Tags/Property tree" org-match-sparse-tree t])
  20060. "--"
  20061. ["Export/Publish..." org-export-dispatch t]
  20062. ("LaTeX"
  20063. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  20064. :selected org-cdlatex-mode]
  20065. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  20066. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  20067. ["Modify math symbol" org-cdlatex-math-modify
  20068. (org-inside-LaTeX-fragment-p)]
  20069. ["Insert citation" org-reftex-citation t]
  20070. "--"
  20071. ["Template for BEAMER" (org-beamer-insert-options-template) t])
  20072. "--"
  20073. ("MobileOrg"
  20074. ["Push Files and Views" org-mobile-push t]
  20075. ["Get Captured and Flagged" org-mobile-pull t]
  20076. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  20077. "--"
  20078. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  20079. "--"
  20080. ("Documentation"
  20081. ["Show Version" org-version t]
  20082. ["Info Documentation" org-info t])
  20083. ("Customize"
  20084. ["Browse Org Group" org-customize t]
  20085. "--"
  20086. ["Expand This Menu" org-create-customize-menu
  20087. (fboundp 'customize-menu-create)])
  20088. ["Send bug report" org-submit-bug-report t]
  20089. "--"
  20090. ("Refresh/Reload"
  20091. ["Refresh setup current buffer" org-mode-restart t]
  20092. ["Reload Org (after update)" org-reload t]
  20093. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  20094. ))
  20095. (defun org-info (&optional node)
  20096. "Read documentation for Org-mode in the info system.
  20097. With optional NODE, go directly to that node."
  20098. (interactive)
  20099. (info (format "(org)%s" (or node ""))))
  20100. ;;;###autoload
  20101. (defun org-submit-bug-report ()
  20102. "Submit a bug report on Org-mode via mail.
  20103. Don't hesitate to report any problems or inaccurate documentation.
  20104. If you don't have setup sending mail from (X)Emacs, please copy the
  20105. output buffer into your mail program, as it gives us important
  20106. information about your Org-mode version and configuration."
  20107. (interactive)
  20108. (require 'reporter)
  20109. (defvar reporter-prompt-for-summary-p)
  20110. (org-load-modules-maybe)
  20111. (org-require-autoloaded-modules)
  20112. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20113. (reporter-submit-bug-report
  20114. "emacs-orgmode@gnu.org"
  20115. (org-version nil 'full)
  20116. (let (list)
  20117. (save-window-excursion
  20118. (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20119. (delete-other-windows)
  20120. (erase-buffer)
  20121. (insert "You are about to submit a bug report to the Org-mode mailing list.
  20122. We would like to add your full Org-mode and Outline configuration to the
  20123. bug report. This greatly simplifies the work of the maintainer and
  20124. other experts on the mailing list.
  20125. HOWEVER, some variables you have customized may contain private
  20126. information. The names of customers, colleagues, or friends, might
  20127. appear in the form of file names, tags, todo states, or search strings.
  20128. If you answer yes to the prompt, you might want to check and remove
  20129. such private information before sending the email.")
  20130. (add-text-properties (point-min) (point-max) '(face org-warning))
  20131. (when (yes-or-no-p "Include your Org-mode configuration ")
  20132. (mapatoms
  20133. (lambda (v)
  20134. (and (boundp v)
  20135. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20136. (or (and (symbol-value v)
  20137. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20138. (and
  20139. (get v 'custom-type) (get v 'standard-value)
  20140. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20141. (push v list)))))
  20142. (kill-buffer (get-buffer "*Warn about privacy*"))
  20143. list))
  20144. nil nil
  20145. "Remember to cover the basics, that is, what you expected to happen and
  20146. what in fact did happen. You don't know how to make a good report? See
  20147. http://orgmode.org/manual/Feedback.html#Feedback
  20148. Your bug report will be posted to the Org-mode mailing list.
  20149. ------------------------------------------------------------------------")
  20150. (save-excursion
  20151. (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20152. (replace-match "\\1Bug: \\3 [\\2]")))))
  20153. (defun org-install-agenda-files-menu ()
  20154. (let ((bl (buffer-list)))
  20155. (save-excursion
  20156. (while bl
  20157. (set-buffer (pop bl))
  20158. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20159. (when (derived-mode-p 'org-mode)
  20160. (easy-menu-change
  20161. '("Org") "File List for Agenda"
  20162. (append
  20163. (list
  20164. ["Edit File List" (org-edit-agenda-file-list) t]
  20165. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20166. ["Remove Current File from List" org-remove-file t]
  20167. ["Cycle through agenda files" org-cycle-agenda-files t]
  20168. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20169. "--")
  20170. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20171. ;;;; Documentation
  20172. (defun org-require-autoloaded-modules ()
  20173. (interactive)
  20174. (mapc 'require
  20175. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20176. org-table org-timer)))
  20177. ;;;###autoload
  20178. (defun org-reload (&optional uncompiled)
  20179. "Reload all org lisp files.
  20180. With prefix arg UNCOMPILED, load the uncompiled versions."
  20181. (interactive "P")
  20182. (require 'loadhist)
  20183. (let* ((org-dir (org-find-library-dir "org"))
  20184. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20185. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20186. (remove-re (mapconcat 'identity
  20187. (mapcar (lambda (f) (concat "^" f "$"))
  20188. (list (if (featurep 'xemacs)
  20189. "org-colview"
  20190. "org-colview-xemacs")
  20191. "org" "org-loaddefs" "org-version"))
  20192. "\\|"))
  20193. (feats (delete-dups
  20194. (mapcar 'file-name-sans-extension
  20195. (mapcar 'file-name-nondirectory
  20196. (delq nil
  20197. (mapcar 'feature-file
  20198. features))))))
  20199. (lfeat (append
  20200. (sort
  20201. (setq feats
  20202. (delq nil (mapcar
  20203. (lambda (f)
  20204. (if (and (string-match feature-re f)
  20205. (not (string-match remove-re f)))
  20206. f nil))
  20207. feats)))
  20208. 'string-lessp)
  20209. (list "org-version" "org")))
  20210. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20211. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20212. load-uncore load-misses)
  20213. (setq load-misses
  20214. (delq 't
  20215. (mapcar (lambda (f)
  20216. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20217. (and (string= org-dir contrib-dir)
  20218. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20219. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20220. (add-to-list 'load-uncore f 'append)
  20221. 't)
  20222. f))
  20223. lfeat)))
  20224. (when load-uncore
  20225. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20226. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20227. (if load-misses
  20228. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20229. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20230. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20231. ;;;###autoload
  20232. (defun org-customize ()
  20233. "Call the customize function with org as argument."
  20234. (interactive)
  20235. (org-load-modules-maybe)
  20236. (org-require-autoloaded-modules)
  20237. (customize-browse 'org))
  20238. (defun org-create-customize-menu ()
  20239. "Create a full customization menu for Org-mode, insert it into the menu."
  20240. (interactive)
  20241. (org-load-modules-maybe)
  20242. (org-require-autoloaded-modules)
  20243. (if (fboundp 'customize-menu-create)
  20244. (progn
  20245. (easy-menu-change
  20246. '("Org") "Customize"
  20247. `(["Browse Org group" org-customize t]
  20248. "--"
  20249. ,(customize-menu-create 'org)
  20250. ["Set" Custom-set t]
  20251. ["Save" Custom-save t]
  20252. ["Reset to Current" Custom-reset-current t]
  20253. ["Reset to Saved" Custom-reset-saved t]
  20254. ["Reset to Standard Settings" Custom-reset-standard t]))
  20255. (message "\"Org\"-menu now contains full customization menu"))
  20256. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20257. ;;;; Miscellaneous stuff
  20258. ;;; Generally useful functions
  20259. (defsubst org-get-at-eol (property n)
  20260. "Get text property PROPERTY at the end of line less N characters."
  20261. (get-text-property (- (point-at-eol) n) property))
  20262. (defun org-find-text-property-in-string (prop s)
  20263. "Return the first non-nil value of property PROP in string S."
  20264. (or (get-text-property 0 prop s)
  20265. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20266. prop s)))
  20267. (defun org-display-warning (message) ;; Copied from Emacs-Muse
  20268. "Display the given MESSAGE as a warning."
  20269. (if (fboundp 'display-warning)
  20270. (display-warning 'org message
  20271. (if (featurep 'xemacs) 'warning :warning))
  20272. (let ((buf (get-buffer-create "*Org warnings*")))
  20273. (with-current-buffer buf
  20274. (goto-char (point-max))
  20275. (insert "Warning (Org): " message)
  20276. (unless (bolp)
  20277. (newline)))
  20278. (display-buffer buf)
  20279. (sit-for 0))))
  20280. (defun org-eval (form)
  20281. "Eval FORM and return result."
  20282. (condition-case error
  20283. (eval form)
  20284. (error (format "%%![Error: %s]" error))))
  20285. (defun org-in-clocktable-p ()
  20286. "Check if the cursor is in a clocktable."
  20287. (let ((pos (point)) start)
  20288. (save-excursion
  20289. (end-of-line 1)
  20290. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20291. (setq start (match-beginning 0))
  20292. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20293. (>= (match-end 0) pos)
  20294. start))))
  20295. (defun org-in-verbatim-emphasis ()
  20296. (save-match-data
  20297. (and (org-in-regexp org-emph-re 2)
  20298. (>= (point) (match-beginning 3))
  20299. (<= (point) (match-end 4))
  20300. (member (match-string 3) '("=" "~")))))
  20301. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20302. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20303. (if (and marker (marker-buffer marker)
  20304. (buffer-live-p (marker-buffer marker)))
  20305. (progn
  20306. (org-pop-to-buffer-same-window (marker-buffer marker))
  20307. (when (or (> marker (point-max)) (< marker (point-min)))
  20308. (widen))
  20309. (goto-char marker)
  20310. (org-show-context 'org-goto))
  20311. (if bookmark
  20312. (bookmark-jump bookmark)
  20313. (error "Cannot find location"))))
  20314. (defun org-quote-csv-field (s)
  20315. "Quote field for inclusion in CSV material."
  20316. (if (string-match "[\",]" s)
  20317. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20318. s))
  20319. (defun org-force-self-insert (N)
  20320. "Needed to enforce self-insert under remapping."
  20321. (interactive "p")
  20322. (self-insert-command N))
  20323. (defun org-string-width (s)
  20324. "Compute width of string, ignoring invisible characters.
  20325. This ignores character with invisibility property `org-link', and also
  20326. characters with property `org-cwidth', because these will become invisible
  20327. upon the next fontification round."
  20328. (let (b l)
  20329. (when (or (eq t buffer-invisibility-spec)
  20330. (assq 'org-link buffer-invisibility-spec))
  20331. (while (setq b (text-property-any 0 (length s)
  20332. 'invisible 'org-link s))
  20333. (setq s (concat (substring s 0 b)
  20334. (substring s (or (next-single-property-change
  20335. b 'invisible s)
  20336. (length s)))))))
  20337. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20338. (setq s (concat (substring s 0 b)
  20339. (substring s (or (next-single-property-change
  20340. b 'org-cwidth s)
  20341. (length s))))))
  20342. (setq l (string-width s) b -1)
  20343. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20344. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20345. l))
  20346. (defun org-shorten-string (s maxlength)
  20347. "Shorten string S so tht it is no longer than MAXLENGTH characters.
  20348. If the string is shorter or has length MAXLENGTH, just return the
  20349. original string. If it is longer, the functions finds a space in the
  20350. string, breaks this string off at that locations and adds three dots
  20351. as ellipsis. Including the ellipsis, the string will not be longer
  20352. than MAXLENGTH. If finding a good breaking point in the string does
  20353. not work, the string is just chopped off in the middle of a word
  20354. if necessary."
  20355. (if (<= (length s) maxlength)
  20356. s
  20357. (let* ((n (max (- maxlength 4) 1))
  20358. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20359. (if (string-match re s)
  20360. (concat (match-string 1 s) "...")
  20361. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20362. (defun org-get-indentation (&optional line)
  20363. "Get the indentation of the current line, interpreting tabs.
  20364. When LINE is given, assume it represents a line and compute its indentation."
  20365. (if line
  20366. (when (string-match "^ *" (org-remove-tabs line))
  20367. (match-end 0))
  20368. (save-excursion
  20369. (beginning-of-line 1)
  20370. (skip-chars-forward " \t")
  20371. (current-column))))
  20372. (defun org-get-string-indentation (s)
  20373. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20374. (let ((n -1) (i 0) (w tab-width) c)
  20375. (catch 'exit
  20376. (while (< (setq n (1+ n)) (length s))
  20377. (setq c (aref s n))
  20378. (cond ((= c ?\ ) (setq i (1+ i)))
  20379. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20380. (t (throw 'exit t)))))
  20381. i))
  20382. (defun org-remove-tabs (s &optional width)
  20383. "Replace tabulators in S with spaces.
  20384. Assumes that s is a single line, starting in column 0."
  20385. (setq width (or width tab-width))
  20386. (while (string-match "\t" s)
  20387. (setq s (replace-match
  20388. (make-string
  20389. (- (* width (/ (+ (match-beginning 0) width) width))
  20390. (match-beginning 0)) ?\ )
  20391. t t s)))
  20392. s)
  20393. (defun org-fix-indentation (line ind)
  20394. "Fix indentation in LINE.
  20395. IND is a cons cell with target and minimum indentation.
  20396. If the current indentation in LINE is smaller than the minimum,
  20397. leave it alone. If it is larger than ind, set it to the target."
  20398. (let* ((l (org-remove-tabs line))
  20399. (i (org-get-indentation l))
  20400. (i1 (car ind)) (i2 (cdr ind)))
  20401. (when (>= i i2) (setq l (substring line i2)))
  20402. (if (> i1 0)
  20403. (concat (make-string i1 ?\ ) l)
  20404. l)))
  20405. (defun org-remove-indentation (code &optional n)
  20406. "Remove maximum common indentation in string CODE and return it.
  20407. N may optionally be the number of columns to remove. Return CODE
  20408. as-is if removal failed."
  20409. (with-temp-buffer
  20410. (insert code)
  20411. (if (org-do-remove-indentation n) (buffer-string) code)))
  20412. (defun org-do-remove-indentation (&optional n)
  20413. "Remove the maximum common indentation from the buffer.
  20414. When optional argument N is a positive integer, remove exactly
  20415. that much characters from indentation, if possible. Return nil
  20416. if it fails."
  20417. (catch :exit
  20418. (goto-char (point-min))
  20419. ;; Find maximum common indentation, if not specified.
  20420. (let ((n (or n
  20421. (let ((min-ind (point-max)))
  20422. (save-excursion
  20423. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20424. (let ((ind (1- (current-column))))
  20425. (if (zerop ind) (throw :exit nil)
  20426. (setq min-ind (min min-ind ind))))))
  20427. min-ind))))
  20428. (if (zerop n) (throw :exit nil)
  20429. ;; Remove exactly N indentation, but give up if not possible.
  20430. (while (not (eobp))
  20431. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20432. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20433. ((< ind n) (throw :exit nil))
  20434. (t (org-indent-line-to (- ind n))))
  20435. (forward-line)))
  20436. ;; Signal success.
  20437. t))))
  20438. (defun org-fill-template (template alist)
  20439. "Find each %key of ALIST in TEMPLATE and replace it."
  20440. (let ((case-fold-search nil))
  20441. (dolist (entry (sort (copy-sequence alist)
  20442. (lambda (a b) (< (length (car a)) (length (car b))))))
  20443. (setq template
  20444. (replace-regexp-in-string
  20445. (concat "%" (regexp-quote (car entry)))
  20446. (or (cdr entry) "") template t t)))
  20447. template))
  20448. (defun org-base-buffer (buffer)
  20449. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20450. (if (not buffer)
  20451. buffer
  20452. (or (buffer-base-buffer buffer)
  20453. buffer)))
  20454. (defun org-wrap (string &optional width lines)
  20455. "Wrap string to either a number of lines, or a width in characters.
  20456. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20457. that costs. If there is a word longer than WIDTH, the text is actually
  20458. wrapped to the length of that word.
  20459. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20460. many lines, whatever width that takes.
  20461. The return value is a list of lines, without newlines at the end."
  20462. (let* ((words (org-split-string string "[ \t\n]+"))
  20463. (maxword (apply 'max (mapcar 'org-string-width words)))
  20464. w ll)
  20465. (cond (width
  20466. (org-do-wrap words (max maxword width)))
  20467. (lines
  20468. (setq w maxword)
  20469. (setq ll (org-do-wrap words maxword))
  20470. (if (<= (length ll) lines)
  20471. ll
  20472. (setq ll words)
  20473. (while (> (length ll) lines)
  20474. (setq w (1+ w))
  20475. (setq ll (org-do-wrap words w)))
  20476. ll))
  20477. (t (error "Cannot wrap this")))))
  20478. (defun org-do-wrap (words width)
  20479. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20480. (let (lines line)
  20481. (while words
  20482. (setq line (pop words))
  20483. (while (and words (< (+ (length line) (length (car words))) width))
  20484. (setq line (concat line " " (pop words))))
  20485. (setq lines (push line lines)))
  20486. (nreverse lines)))
  20487. (defun org-split-string (string &optional separators)
  20488. "Splits STRING into substrings at SEPARATORS.
  20489. SEPARATORS is a regular expression.
  20490. No empty strings are returned if there are matches at the beginning
  20491. and end of string."
  20492. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20493. (let ((start 0) notfirst list)
  20494. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20495. (if (and notfirst
  20496. (= start (match-beginning 0))
  20497. (< start (length string)))
  20498. (1+ start) start))
  20499. (< (match-beginning 0) (length string)))
  20500. (setq notfirst t)
  20501. (or (eq (match-beginning 0) 0)
  20502. (and (eq (match-beginning 0) (match-end 0))
  20503. (eq (match-beginning 0) start))
  20504. (push (substring string start (match-beginning 0)) list))
  20505. (setq start (match-end 0)))
  20506. (or (eq start (length string))
  20507. (push (substring string start) list))
  20508. (nreverse list)))
  20509. (defun org-quote-vert (s)
  20510. "Replace \"|\" with \"\\vert\"."
  20511. (while (string-match "|" s)
  20512. (setq s (replace-match "\\vert" t t s)))
  20513. s)
  20514. (defun org-uuidgen-p (s)
  20515. "Is S an ID created by UUIDGEN?"
  20516. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20517. (defun org-in-src-block-p (&optional inside)
  20518. "Whether point is in a code source block.
  20519. When INSIDE is non-nil, don't consider we are within a src block
  20520. when point is at #+BEGIN_SRC or #+END_SRC."
  20521. (let ((case-fold-search t))
  20522. (or (and (eq (get-char-property (point) 'src-block) t))
  20523. (and (not inside)
  20524. (save-match-data
  20525. (save-excursion
  20526. (beginning-of-line)
  20527. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20528. (defun org-context ()
  20529. "Return a list of contexts of the current cursor position.
  20530. If several contexts apply, all are returned.
  20531. Each context entry is a list with a symbol naming the context, and
  20532. two positions indicating start and end of the context. Possible
  20533. contexts are:
  20534. :headline anywhere in a headline
  20535. :headline-stars on the leading stars in a headline
  20536. :todo-keyword on a TODO keyword (including DONE) in a headline
  20537. :tags on the TAGS in a headline
  20538. :priority on the priority cookie in a headline
  20539. :item on the first line of a plain list item
  20540. :item-bullet on the bullet/number of a plain list item
  20541. :checkbox on the checkbox in a plain list item
  20542. :table in an org-mode table
  20543. :table-special on a special filed in a table
  20544. :table-table in a table.el table
  20545. :clocktable in a clocktable
  20546. :src-block in a source block
  20547. :link on a hyperlink
  20548. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20549. :target on a <<target>>
  20550. :radio-target on a <<<radio-target>>>
  20551. :latex-fragment on a LaTeX fragment
  20552. :latex-preview on a LaTeX fragment with overlaid preview image
  20553. This function expects the position to be visible because it uses font-lock
  20554. faces as a help to recognize the following contexts: :table-special, :link,
  20555. and :keyword."
  20556. (let* ((f (get-text-property (point) 'face))
  20557. (faces (if (listp f) f (list f)))
  20558. (case-fold-search t)
  20559. (p (point)) clist o)
  20560. ;; First the large context
  20561. (cond
  20562. ((org-at-heading-p t)
  20563. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20564. (when (progn
  20565. (beginning-of-line 1)
  20566. (looking-at org-todo-line-tags-regexp))
  20567. (push (org-point-in-group p 1 :headline-stars) clist)
  20568. (push (org-point-in-group p 2 :todo-keyword) clist)
  20569. (push (org-point-in-group p 4 :tags) clist))
  20570. (goto-char p)
  20571. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20572. (when (looking-at "\\[#[A-Z0-9]\\]")
  20573. (push (org-point-in-group p 0 :priority) clist)))
  20574. ((org-at-item-p)
  20575. (push (org-point-in-group p 2 :item-bullet) clist)
  20576. (push (list :item (point-at-bol)
  20577. (save-excursion (org-end-of-item) (point)))
  20578. clist)
  20579. (and (org-at-item-checkbox-p)
  20580. (push (org-point-in-group p 0 :checkbox) clist)))
  20581. ((org-at-table-p)
  20582. (push (list :table (org-table-begin) (org-table-end)) clist)
  20583. (when (memq 'org-formula faces)
  20584. (push (list :table-special
  20585. (previous-single-property-change p 'face)
  20586. (next-single-property-change p 'face)) clist)))
  20587. ((org-at-table-p 'any)
  20588. (push (list :table-table) clist)))
  20589. (goto-char p)
  20590. (let ((case-fold-search t))
  20591. ;; New the "medium" contexts: clocktables, source blocks
  20592. (cond ((org-in-clocktable-p)
  20593. (push (list :clocktable
  20594. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20595. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20596. (match-beginning 1))
  20597. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20598. (match-end 0))) clist))
  20599. ((org-in-src-block-p)
  20600. (push (list :src-block
  20601. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20602. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20603. (match-beginning 1))
  20604. (and (search-forward "#+END_SRC" nil t)
  20605. (match-beginning 0))) clist))))
  20606. (goto-char p)
  20607. ;; Now the small context
  20608. (cond
  20609. ((org-at-timestamp-p)
  20610. (push (org-point-in-group p 0 :timestamp) clist))
  20611. ((memq 'org-link faces)
  20612. (push (list :link
  20613. (previous-single-property-change p 'face)
  20614. (next-single-property-change p 'face)) clist))
  20615. ((memq 'org-special-keyword faces)
  20616. (push (list :keyword
  20617. (previous-single-property-change p 'face)
  20618. (next-single-property-change p 'face)) clist))
  20619. ((org-at-target-p)
  20620. (push (org-point-in-group p 0 :target) clist)
  20621. (goto-char (1- (match-beginning 0)))
  20622. (when (looking-at org-radio-target-regexp)
  20623. (push (org-point-in-group p 0 :radio-target) clist))
  20624. (goto-char p))
  20625. ((setq o (car (delq nil
  20626. (mapcar
  20627. (lambda (x)
  20628. (when (memq x org-latex-fragment-image-overlays) x))
  20629. (overlays-at (point))))))
  20630. (push (list :latex-fragment
  20631. (overlay-start o) (overlay-end o)) clist)
  20632. (push (list :latex-preview
  20633. (overlay-start o) (overlay-end o)) clist))
  20634. ((org-inside-LaTeX-fragment-p)
  20635. ;; FIXME: positions wrong.
  20636. (push (list :latex-fragment (point) (point)) clist)))
  20637. (setq clist (nreverse (delq nil clist)))
  20638. clist))
  20639. (defun org-in-regexp (regexp &optional nlines visually)
  20640. "Check if point is inside a match of REGEXP.
  20641. Normally only the current line is checked, but you can include
  20642. NLINES extra lines around point into the search. If VISUALLY is
  20643. set, require that the cursor is not after the match but really
  20644. on, so that the block visually is on the match.
  20645. Return nil or a cons cell (BEG . END) where BEG and END are,
  20646. respectively, the positions at the beginning and the end of the
  20647. match."
  20648. (catch :exit
  20649. (let ((pos (point))
  20650. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20651. (save-excursion
  20652. (beginning-of-line (- 1 (or nlines 0)))
  20653. (while (and (re-search-forward regexp eol t)
  20654. (<= (match-beginning 0) pos))
  20655. (let ((end (match-end 0)))
  20656. (when (or (> end pos) (and (= end pos) (not visually)))
  20657. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20658. (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
  20659. "Org mode 8.3")
  20660. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20661. "Non-nil when point is between matches of START-RE and END-RE.
  20662. Also return a non-nil value when point is on one of the matches.
  20663. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20664. buffer positions. Default values are the positions of headlines
  20665. surrounding the point.
  20666. The functions returns a cons cell whose car (resp. cdr) is the
  20667. position before START-RE (resp. after END-RE)."
  20668. (save-match-data
  20669. (let ((pos (point))
  20670. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20671. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20672. beg end)
  20673. (save-excursion
  20674. ;; Point is on a block when on START-RE or if START-RE can be
  20675. ;; found before it...
  20676. (and (or (org-in-regexp start-re)
  20677. (re-search-backward start-re limit-up t))
  20678. (setq beg (match-beginning 0))
  20679. ;; ... and END-RE after it...
  20680. (goto-char (match-end 0))
  20681. (re-search-forward end-re limit-down t)
  20682. (> (setq end (match-end 0)) pos)
  20683. ;; ... without another START-RE in-between.
  20684. (goto-char (match-beginning 0))
  20685. (not (re-search-backward start-re (1+ beg) t))
  20686. ;; Return value.
  20687. (cons beg end))))))
  20688. (defun org-in-block-p (names)
  20689. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20690. NAMES is a list of strings containing names of blocks.
  20691. Return first block name matched, or nil. Beware that in case of
  20692. nested blocks, the returned name may not belong to the closest
  20693. block from point."
  20694. (save-match-data
  20695. (catch 'exit
  20696. (let ((case-fold-search t)
  20697. (lim-up (save-excursion (outline-previous-heading)))
  20698. (lim-down (save-excursion (outline-next-heading))))
  20699. (mapc (lambda (name)
  20700. (let ((n (regexp-quote name)))
  20701. (when (org-between-regexps-p
  20702. (concat "^[ \t]*#\\+begin_" n)
  20703. (concat "^[ \t]*#\\+end_" n)
  20704. lim-up lim-down)
  20705. (throw 'exit n))))
  20706. names))
  20707. nil)))
  20708. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20709. "Call `multi-occur' with buffers for all agenda files."
  20710. (interactive "sOrg-files matching: ")
  20711. (let* ((files (org-agenda-files))
  20712. (tnames (mapcar #'file-truename files))
  20713. (extra org-agenda-text-search-extra-files))
  20714. (when (eq (car extra) 'agenda-archives)
  20715. (setq extra (cdr extra))
  20716. (setq files (org-add-archive-files files)))
  20717. (dolist (f extra)
  20718. (unless (member (file-truename f) tnames)
  20719. (unless (member f files) (setq files (append files (list f))))
  20720. (setq tnames (append tnames (list (file-truename f))))))
  20721. (multi-occur
  20722. (mapcar (lambda (x)
  20723. (with-current-buffer
  20724. ;; FIXME: Why not just (find-file-noselect x)?
  20725. ;; Is it to avoid the "revert buffer" prompt?
  20726. (or (get-file-buffer x) (find-file-noselect x))
  20727. (widen)
  20728. (current-buffer)))
  20729. files)
  20730. regexp)))
  20731. (if (boundp 'occur-mode-find-occurrence-hook)
  20732. ;; Emacs 23
  20733. (add-hook 'occur-mode-find-occurrence-hook
  20734. (lambda ()
  20735. (when (derived-mode-p 'org-mode)
  20736. (org-reveal))))
  20737. ;; Emacs 22
  20738. (defadvice occur-mode-goto-occurrence
  20739. (after org-occur-reveal activate)
  20740. (and (derived-mode-p 'org-mode) (org-reveal)))
  20741. (defadvice occur-mode-goto-occurrence-other-window
  20742. (after org-occur-reveal activate)
  20743. (and (derived-mode-p 'org-mode) (org-reveal)))
  20744. (defadvice occur-mode-display-occurrence
  20745. (after org-occur-reveal activate)
  20746. (when (derived-mode-p 'org-mode)
  20747. (let ((pos (occur-mode-find-occurrence)))
  20748. (with-current-buffer (marker-buffer pos)
  20749. (save-excursion
  20750. (goto-char pos)
  20751. (org-reveal)))))))
  20752. (defun org-occur-link-in-agenda-files ()
  20753. "Create a link and search for it in the agendas.
  20754. The link is not stored in `org-stored-links', it is just created
  20755. for the search purpose."
  20756. (interactive)
  20757. (let ((link (condition-case nil
  20758. (org-store-link nil)
  20759. (error "Unable to create a link to here"))))
  20760. (org-occur-in-agenda-files (regexp-quote link))))
  20761. (defun org-reverse-string (string)
  20762. "Return the reverse of STRING."
  20763. (apply 'string (reverse (string-to-list string))))
  20764. ;; defsubst org-uniquify must be defined before first use
  20765. (defun org-uniquify-alist (alist)
  20766. "Merge elements of ALIST with the same key.
  20767. For example, in this alist:
  20768. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20769. => \\='((a 1 3) (b 2))
  20770. merge (a 1) and (a 3) into (a 1 3).
  20771. The function returns the new ALIST."
  20772. (let (rtn)
  20773. (mapc
  20774. (lambda (e)
  20775. (let (n)
  20776. (if (not (assoc (car e) rtn))
  20777. (push e rtn)
  20778. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20779. (setq rtn (assq-delete-all (car e) rtn))
  20780. (push n rtn))))
  20781. alist)
  20782. rtn))
  20783. (defun org-delete-all (elts list)
  20784. "Remove all elements in ELTS from LIST."
  20785. (while elts
  20786. (setq list (delete (pop elts) list)))
  20787. list)
  20788. (defun org-back-over-empty-lines ()
  20789. "Move backwards over whitespace, to the beginning of the first empty line.
  20790. Returns the number of empty lines passed."
  20791. (let ((pos (point)))
  20792. (if (cdr (assoc 'heading org-blank-before-new-entry))
  20793. (skip-chars-backward " \t\n\r")
  20794. (unless (eobp)
  20795. (forward-line -1)))
  20796. (beginning-of-line 2)
  20797. (goto-char (min (point) pos))
  20798. (count-lines (point) pos)))
  20799. (defun org-skip-whitespace ()
  20800. (skip-chars-forward " \t\n\r"))
  20801. (defun org-point-in-group (point group &optional context)
  20802. "Check if POINT is in match-group GROUP.
  20803. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20804. match. If the match group does not exist or point is not inside it,
  20805. return nil."
  20806. (and (match-beginning group)
  20807. (>= point (match-beginning group))
  20808. (<= point (match-end group))
  20809. (if context
  20810. (list context (match-beginning group) (match-end group))
  20811. t)))
  20812. (defun org-switch-to-buffer-other-window (&rest args)
  20813. "Switch to buffer in a second window on the current frame.
  20814. In particular, do not allow pop-up frames.
  20815. Returns the newly created buffer."
  20816. (org-no-popups
  20817. (apply 'switch-to-buffer-other-window args)))
  20818. (defun org-combine-plists (&rest plists)
  20819. "Create a single property list from all plists in PLISTS.
  20820. The process starts by copying the first list, and then setting properties
  20821. from the other lists. Settings in the last list are the most significant
  20822. ones and overrule settings in the other lists."
  20823. (let ((rtn (copy-sequence (pop plists)))
  20824. p v ls)
  20825. (while plists
  20826. (setq ls (pop plists))
  20827. (while ls
  20828. (setq p (pop ls) v (pop ls))
  20829. (setq rtn (plist-put rtn p v))))
  20830. rtn))
  20831. (defun org-replace-escapes (string table)
  20832. "Replace %-escapes in STRING with values in TABLE.
  20833. TABLE is an association list with keys like \"%a\" and string values.
  20834. The sequences in STRING may contain normal field width and padding information,
  20835. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20836. so values can contain further %-escapes if they are define later in TABLE."
  20837. (let ((tbl (copy-alist table))
  20838. (case-fold-search nil)
  20839. (pchg 0)
  20840. re rpl)
  20841. (dolist (e tbl)
  20842. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20843. (when (and (cdr e) (string-match re (cdr e)))
  20844. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20845. (safe "SREF"))
  20846. (add-text-properties 0 3 (list 'sref sref) safe)
  20847. (setcdr e (replace-match safe t t (cdr e)))))
  20848. (while (string-match re string)
  20849. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20850. (cdr e)))
  20851. (setq string (replace-match rpl t t string))))
  20852. (while (setq pchg (next-property-change pchg string))
  20853. (let ((sref (get-text-property pchg 'sref string)))
  20854. (when (and sref (string-match "SREF" string pchg))
  20855. (setq string (replace-match sref t t string)))))
  20856. string))
  20857. (defun org-sublist (list start end)
  20858. "Return a section of LIST, from START to END.
  20859. Counting starts at 1."
  20860. (cl-subseq list (1- start) end))
  20861. (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
  20862. (defun org-find-base-buffer-visiting (file)
  20863. "Like `find-buffer-visiting' but always return the base buffer and
  20864. not an indirect buffer."
  20865. (let ((buf (or (get-file-buffer file)
  20866. (find-buffer-visiting file))))
  20867. (if buf
  20868. (or (buffer-base-buffer buf) buf)
  20869. nil)))
  20870. (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
  20871. "Org 9.0")
  20872. ;;; TODO: Only called once, from ox-odt which should probably use
  20873. ;;; org-export-inline-image-p or something.
  20874. (defun org-file-image-p (file)
  20875. "Return non-nil if FILE is an image."
  20876. (save-match-data
  20877. (string-match (image-file-name-regexp) file)))
  20878. (defun org-get-cursor-date (&optional with-time)
  20879. "Return the date at cursor in as a time.
  20880. This works in the calendar and in the agenda, anywhere else it just
  20881. returns the current time.
  20882. If WITH-TIME is non-nil, returns the time of the event at point (in
  20883. the agenda) or the current time of the day."
  20884. (let (date day defd tp hod mod)
  20885. (when with-time
  20886. (setq tp (get-text-property (point) 'time))
  20887. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20888. (setq hod (string-to-number (match-string 1 tp))
  20889. mod (string-to-number (match-string 2 tp))))
  20890. (or tp (let ((now (decode-time)))
  20891. (setq hod (nth 2 now)
  20892. mod (nth 1 now)))))
  20893. (cond
  20894. ((eq major-mode 'calendar-mode)
  20895. (setq date (calendar-cursor-to-date)
  20896. defd (encode-time 0 (or mod 0) (or hod 0)
  20897. (nth 1 date) (nth 0 date) (nth 2 date))))
  20898. ((eq major-mode 'org-agenda-mode)
  20899. (setq day (get-text-property (point) 'day))
  20900. (when day
  20901. (setq date (calendar-gregorian-from-absolute day)
  20902. defd (encode-time 0 (or mod 0) (or hod 0)
  20903. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20904. (or defd (current-time))))
  20905. (defun org-mark-subtree (&optional up)
  20906. "Mark the current subtree.
  20907. This puts point at the start of the current subtree, and mark at
  20908. the end. If a numeric prefix UP is given, move up into the
  20909. hierarchy of headlines by UP levels before marking the subtree."
  20910. (interactive "P")
  20911. (org-with-limited-levels
  20912. (cond ((org-at-heading-p) (beginning-of-line))
  20913. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20914. (t (outline-previous-visible-heading 1))))
  20915. (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
  20916. (if (org-called-interactively-p 'any)
  20917. (call-interactively 'org-mark-element)
  20918. (org-mark-element)))
  20919. ;;; Indentation
  20920. (defun org--get-expected-indentation (element contentsp)
  20921. "Expected indentation column for current line, according to ELEMENT.
  20922. ELEMENT is an element containing point. CONTENTSP is non-nil
  20923. when indentation is to be computed according to contents of
  20924. ELEMENT."
  20925. (let ((type (org-element-type element))
  20926. (start (org-element-property :begin element))
  20927. (post-affiliated (org-element-property :post-affiliated element)))
  20928. (org-with-wide-buffer
  20929. (cond
  20930. (contentsp
  20931. (case type
  20932. ((diary-sexp footnote-definition) 0)
  20933. ((headline inlinetask nil)
  20934. (if (not org-adapt-indentation) 0
  20935. (let ((level (org-current-level)))
  20936. (if level (1+ level) 0))))
  20937. ((item plain-list) (org-list-item-body-column post-affiliated))
  20938. (t
  20939. (goto-char start)
  20940. (org-get-indentation))))
  20941. ((memq type '(headline inlinetask nil))
  20942. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20943. (org--get-expected-indentation element t)
  20944. 0))
  20945. ((memq type '(diary-sexp footnote-definition)) 0)
  20946. ;; First paragraph of a footnote definition or an item.
  20947. ;; Indent like parent.
  20948. ((< (line-beginning-position) start)
  20949. (org--get-expected-indentation
  20950. (org-element-property :parent element) t))
  20951. ;; At first line: indent according to previous sibling, if any,
  20952. ;; ignoring footnote definitions and inline tasks, or parent's
  20953. ;; contents.
  20954. ((= (line-beginning-position) start)
  20955. (catch 'exit
  20956. (while t
  20957. (if (= (point-min) start) (throw 'exit 0)
  20958. (goto-char (1- start))
  20959. (let* ((previous (org-element-at-point))
  20960. (parent previous))
  20961. (while (and parent (<= (org-element-property :end parent) start))
  20962. (setq previous parent
  20963. parent (org-element-property :parent parent)))
  20964. (cond
  20965. ((not previous) (throw 'exit 0))
  20966. ((> (org-element-property :end previous) start)
  20967. (throw 'exit (org--get-expected-indentation previous t)))
  20968. ((memq (org-element-type previous)
  20969. '(footnote-definition inlinetask))
  20970. (setq start (org-element-property :begin previous)))
  20971. (t (goto-char (org-element-property :begin previous))
  20972. (throw 'exit
  20973. (if (bolp) (org-get-indentation)
  20974. ;; At first paragraph in an item or
  20975. ;; a footnote definition.
  20976. (org--get-expected-indentation
  20977. (org-element-property :parent previous) t))))))))))
  20978. ;; Otherwise, move to the first non-blank line above.
  20979. (t
  20980. (beginning-of-line)
  20981. (let ((pos (point)))
  20982. (skip-chars-backward " \r\t\n")
  20983. (cond
  20984. ;; Two blank lines end a footnote definition or a plain
  20985. ;; list. When we indent an empty line after them, the
  20986. ;; containing list or footnote definition is over, so it
  20987. ;; qualifies as a previous sibling. Therefore, we indent
  20988. ;; like its first line.
  20989. ((and (memq type '(footnote-definition plain-list))
  20990. (> (count-lines (point) pos) 2))
  20991. (goto-char start)
  20992. (org-get-indentation))
  20993. ;; Line above is the first one of a paragraph at the
  20994. ;; beginning of an item or a footnote definition. Indent
  20995. ;; like parent.
  20996. ((< (line-beginning-position) start)
  20997. (org--get-expected-indentation
  20998. (org-element-property :parent element) t))
  20999. ;; Line above is the beginning of an element, i.e., point
  21000. ;; was originally on the blank lines between element's start
  21001. ;; and contents.
  21002. ((= (line-beginning-position) post-affiliated)
  21003. (org--get-expected-indentation element t))
  21004. ;; POS is after contents in a greater element. Indent like
  21005. ;; the beginning of the element.
  21006. ;;
  21007. ;; As a special case, if point is at the end of a footnote
  21008. ;; definition or an item, indent like the very last element
  21009. ;; within.
  21010. ((and (not (eq type 'paragraph))
  21011. (let ((cend (org-element-property :contents-end element)))
  21012. (and cend (<= cend pos))))
  21013. (if (memq type '(footnote-definition item plain-list))
  21014. (let ((last (org-element-at-point)))
  21015. (org--get-expected-indentation
  21016. last
  21017. (memq (org-element-type last)
  21018. '(footnote-definition item plain-list))))
  21019. (goto-char start)
  21020. (org-get-indentation)))
  21021. ;; In any other case, indent like the current line.
  21022. (t (org-get-indentation)))))))))
  21023. (defun org--align-node-property ()
  21024. "Align node property at point.
  21025. Alignment is done according to `org-property-format', which see."
  21026. (when (save-excursion
  21027. (beginning-of-line)
  21028. (looking-at org-property-re))
  21029. (replace-match
  21030. (concat (match-string 4)
  21031. (org-trim
  21032. (format org-property-format (match-string 1) (match-string 3))))
  21033. t t)))
  21034. (defun org-indent-line ()
  21035. "Indent line depending on context.
  21036. Indentation is done according to the following rules:
  21037. - Footnote definitions, diary sexps, headlines and inline tasks
  21038. have to start at column 0.
  21039. - On the very first line of an element, consider, in order, the
  21040. next rules until one matches:
  21041. 1. If there's a sibling element before, ignoring footnote
  21042. definitions and inline tasks, indent like its first line.
  21043. 2. If element has a parent, indent like its contents. More
  21044. precisely, if parent is an item, indent after the
  21045. description part, if any, or the bullet (see
  21046. `org-list-description-max-indent'). Else, indent like
  21047. parent's first line.
  21048. 3. Otherwise, indent relatively to current level, if
  21049. `org-adapt-indentation' is non-nil, or to left margin.
  21050. - On a blank line at the end of an element, indent according to
  21051. the type of the element. More precisely
  21052. 1. If element is a plain list, an item, or a footnote
  21053. definition, indent like the very last element within.
  21054. 2. If element is a paragraph, indent like its last non blank
  21055. line.
  21056. 3. Otherwise, indent like its very first line.
  21057. - In the code part of a source block, use language major mode
  21058. to indent current line if `org-src-tab-acts-natively' is
  21059. non-nil. If it is nil, do nothing.
  21060. - Otherwise, indent like the first non-blank line above.
  21061. The function doesn't indent an item as it could break the whole
  21062. list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
  21063. \\[org-shiftmetaright].
  21064. Also align node properties according to `org-property-format'."
  21065. (interactive)
  21066. (cond
  21067. (orgstruct-is-++
  21068. (let ((indent-line-function
  21069. (cadadr (assq 'indent-line-function org-fb-vars))))
  21070. (indent-according-to-mode)))
  21071. ((org-at-heading-p) 'noindent)
  21072. (t
  21073. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  21074. (type (org-element-type element)))
  21075. (cond ((and (memq type '(plain-list item))
  21076. (= (line-beginning-position)
  21077. (org-element-property :post-affiliated element)))
  21078. 'noindent)
  21079. ((and (eq type 'src-block)
  21080. org-src-tab-acts-natively
  21081. (> (line-beginning-position)
  21082. (org-element-property :post-affiliated element))
  21083. (< (line-beginning-position)
  21084. (org-with-wide-buffer
  21085. (goto-char (org-element-property :end element))
  21086. (skip-chars-backward " \r\t\n")
  21087. (line-beginning-position))))
  21088. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21089. (t
  21090. (let ((column (org--get-expected-indentation element nil)))
  21091. ;; Preserve current column.
  21092. (if (<= (current-column) (current-indentation))
  21093. (org-indent-line-to column)
  21094. (save-excursion (org-indent-line-to column))))
  21095. ;; Align node property. Also preserve current column.
  21096. (when (eq type 'node-property)
  21097. (let ((column (current-column)))
  21098. (org--align-node-property)
  21099. (org-move-to-column column)))))))))
  21100. (defun org-indent-region (start end)
  21101. "Indent each non-blank line in the region.
  21102. Called from a program, START and END specify the region to
  21103. indent. The function will not indent contents of example blocks,
  21104. verse blocks and export blocks as leading white spaces are
  21105. assumed to be significant there."
  21106. (interactive "r")
  21107. (save-excursion
  21108. (goto-char start)
  21109. (skip-chars-forward " \r\t\n")
  21110. (unless (eobp) (beginning-of-line))
  21111. (let ((indent-to
  21112. (lambda (ind pos)
  21113. ;; Set IND as indentation for all lines between point and
  21114. ;; POS. Blank lines are ignored. Leave point after POS
  21115. ;; once done.
  21116. (let ((limit (copy-marker pos)))
  21117. (while (< (point) limit)
  21118. (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
  21119. (forward-line))
  21120. (set-marker limit nil))))
  21121. (end (copy-marker end)))
  21122. (while (< (point) end)
  21123. (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21124. (let* ((element (org-element-at-point))
  21125. (type (org-element-type element))
  21126. (element-end (copy-marker (org-element-property :end element)))
  21127. (ind (org--get-expected-indentation element nil)))
  21128. (cond
  21129. ((or (memq type '(paragraph table table-row))
  21130. (not (or (org-element-property :contents-begin element)
  21131. (memq type
  21132. '(example-block export-block src-block)))))
  21133. ;; Elements here are indented as a single block. Also
  21134. ;; align node properties.
  21135. (when (eq type 'node-property)
  21136. (org--align-node-property)
  21137. (beginning-of-line))
  21138. (funcall indent-to ind (min element-end end)))
  21139. (t
  21140. ;; Elements in this category consist of three parts:
  21141. ;; before the contents, the contents, and after the
  21142. ;; contents. The contents are treated specially,
  21143. ;; according to the element type, or not indented at
  21144. ;; all. Other parts are indented as a single block.
  21145. (let* ((post (copy-marker
  21146. (org-element-property :post-affiliated element)))
  21147. (cbeg
  21148. (copy-marker
  21149. (cond
  21150. ((not (org-element-property :contents-begin element))
  21151. ;; Fake contents for source blocks.
  21152. (org-with-wide-buffer
  21153. (goto-char post)
  21154. (forward-line)
  21155. (point)))
  21156. ((memq type '(footnote-definition item plain-list))
  21157. ;; Contents in these elements could start on
  21158. ;; the same line as the beginning of the
  21159. ;; element. Make sure we start indenting
  21160. ;; from the second line.
  21161. (org-with-wide-buffer
  21162. (goto-char post)
  21163. (end-of-line)
  21164. (skip-chars-forward " \r\t\n")
  21165. (if (eobp) (point) (line-beginning-position))))
  21166. (t (org-element-property :contents-begin element)))))
  21167. (cend (copy-marker
  21168. (or (org-element-property :contents-end element)
  21169. ;; Fake contents for source blocks.
  21170. (org-with-wide-buffer
  21171. (goto-char element-end)
  21172. (skip-chars-backward " \r\t\n")
  21173. (line-beginning-position)))
  21174. t)))
  21175. ;; Do not change items indentation individually as it
  21176. ;; might break the list as a whole. On the other
  21177. ;; hand, when at a plain list, indent it as a whole.
  21178. (cond ((eq type 'plain-list)
  21179. (let ((offset (- ind (org-get-indentation))))
  21180. (unless (zerop offset)
  21181. (indent-rigidly (org-element-property :begin element)
  21182. (org-element-property :end element)
  21183. offset))
  21184. (goto-char cbeg)))
  21185. ((eq type 'item) (goto-char cbeg))
  21186. (t (funcall indent-to ind (min cbeg end))))
  21187. (when (< (point) end)
  21188. (case type
  21189. ((example-block export-block verse-block))
  21190. (src-block
  21191. ;; In a source block, indent source code
  21192. ;; according to language major mode, but only if
  21193. ;; `org-src-tab-acts-natively' is non-nil.
  21194. (when (and (< (point) end) org-src-tab-acts-natively)
  21195. (ignore-errors
  21196. (org-babel-do-in-edit-buffer
  21197. (indent-region (point-min) (point-max))))))
  21198. (t (org-indent-region (point) (min cend end))))
  21199. (goto-char (min cend end))
  21200. (when (< (point) end)
  21201. (funcall indent-to ind (min element-end end))))
  21202. (set-marker post nil)
  21203. (set-marker cbeg nil)
  21204. (set-marker cend nil))))
  21205. (set-marker element-end nil))))
  21206. (set-marker end nil))))
  21207. (defun org-indent-drawer ()
  21208. "Indent the drawer at point."
  21209. (interactive)
  21210. (unless (save-excursion
  21211. (beginning-of-line)
  21212. (org-looking-at-p org-drawer-regexp))
  21213. (user-error "Not at a drawer"))
  21214. (let ((element (org-element-at-point)))
  21215. (unless (memq (org-element-type element) '(drawer property-drawer))
  21216. (user-error "Not at a drawer"))
  21217. (org-with-wide-buffer
  21218. (org-indent-region (org-element-property :begin element)
  21219. (org-element-property :end element))))
  21220. (message "Drawer at point indented"))
  21221. (defun org-indent-block ()
  21222. "Indent the block at point."
  21223. (interactive)
  21224. (unless (save-excursion
  21225. (beginning-of-line)
  21226. (let ((case-fold-search t))
  21227. (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21228. (user-error "Not at a block"))
  21229. (let ((element (org-element-at-point)))
  21230. (unless (memq (org-element-type element)
  21231. '(comment-block center-block dynamic-block example-block
  21232. export-block quote-block special-block
  21233. src-block verse-block))
  21234. (user-error "Not at a block"))
  21235. (org-with-wide-buffer
  21236. (org-indent-region (org-element-property :begin element)
  21237. (org-element-property :end element))))
  21238. (message "Block at point indented"))
  21239. ;;; Filling
  21240. ;; We use our own fill-paragraph and auto-fill functions.
  21241. ;; `org-fill-paragraph' relies on adaptive filling and context
  21242. ;; checking. Appropriate `fill-prefix' is computed with
  21243. ;; `org-adaptive-fill-function'.
  21244. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21245. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21246. ;; `org-adaptive-fill-function' value. Internally,
  21247. ;; `org-comment-line-break-function' breaks the line.
  21248. ;; `org-setup-filling' installs filling and auto-filling related
  21249. ;; variables during `org-mode' initialization.
  21250. (defvar org-element-paragraph-separate) ; org-element.el
  21251. (defun org-setup-filling ()
  21252. (require 'org-element)
  21253. ;; Prevent auto-fill from inserting unwanted new items.
  21254. (when (boundp 'fill-nobreak-predicate)
  21255. (setq-local
  21256. fill-nobreak-predicate
  21257. (org-uniquify
  21258. (append fill-nobreak-predicate
  21259. '(org-fill-line-break-nobreak-p
  21260. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21261. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21262. (setq-local paragraph-start paragraph-ending)
  21263. (setq-local paragraph-separate paragraph-ending))
  21264. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21265. (setq-local auto-fill-inhibit-regexp nil)
  21266. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21267. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21268. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21269. (defun org-fill-line-break-nobreak-p ()
  21270. "Non-nil when a new line at point would create an Org line break."
  21271. (save-excursion
  21272. (skip-chars-backward "[ \t]")
  21273. (skip-chars-backward "\\\\")
  21274. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21275. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21276. "Non-nil when a new line at point would split a timestamp."
  21277. (and (org-at-timestamp-p t)
  21278. (not (looking-at org-ts-regexp-both))))
  21279. (declare-function message-in-body-p "message" ())
  21280. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21281. (defun org-adaptive-fill-function ()
  21282. "Compute a fill prefix for the current line.
  21283. Return fill prefix, as a string, or nil if current line isn't
  21284. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21285. matches in paragraphs or comments, use it."
  21286. (catch 'exit
  21287. (when (derived-mode-p 'message-mode)
  21288. (save-excursion
  21289. (beginning-of-line)
  21290. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21291. ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
  21292. ((looking-at message-cite-prefix-regexp)
  21293. (throw 'exit (match-string-no-properties 0)))
  21294. ((looking-at org-outline-regexp)
  21295. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21296. (org-with-wide-buffer
  21297. (unless (org-at-heading-p)
  21298. (let* ((p (line-beginning-position))
  21299. (element (save-excursion
  21300. (beginning-of-line)
  21301. (org-element-at-point)))
  21302. (type (org-element-type element))
  21303. (post-affiliated (org-element-property :post-affiliated element)))
  21304. (unless (< p post-affiliated)
  21305. (case type
  21306. (comment
  21307. (save-excursion
  21308. (beginning-of-line)
  21309. (looking-at "[ \t]*")
  21310. (concat (match-string 0) "# ")))
  21311. (footnote-definition "")
  21312. ((item plain-list)
  21313. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21314. (paragraph
  21315. ;; Fill prefix is usually the same as the current line,
  21316. ;; unless the paragraph is at the beginning of an item.
  21317. (let ((parent (org-element-property :parent element)))
  21318. (save-excursion
  21319. (beginning-of-line)
  21320. (cond ((eq (org-element-type parent) 'item)
  21321. (make-string (org-list-item-body-column
  21322. (org-element-property :begin parent))
  21323. ?\s))
  21324. ((and adaptive-fill-regexp
  21325. ;; Locally disable
  21326. ;; `adaptive-fill-function' to let
  21327. ;; `fill-context-prefix' handle
  21328. ;; `adaptive-fill-regexp' variable.
  21329. (let (adaptive-fill-function)
  21330. (fill-context-prefix
  21331. post-affiliated
  21332. (org-element-property :end element)))))
  21333. ((looking-at "[ \t]+") (match-string 0))
  21334. (t "")))))
  21335. (comment-block
  21336. ;; Only fill contents if P is within block boundaries.
  21337. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21338. (forward-line)
  21339. (point)))
  21340. (cend (save-excursion
  21341. (goto-char (org-element-property :end element))
  21342. (skip-chars-backward " \r\t\n")
  21343. (line-beginning-position))))
  21344. (when (and (>= p cbeg) (< p cend))
  21345. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21346. (match-string 0)
  21347. "")))))))))))
  21348. (declare-function message-goto-body "message" ())
  21349. (defvar message-cite-prefix-regexp) ; From message.el
  21350. (defun org-fill-paragraph (&optional justify)
  21351. "Fill element at point, when applicable.
  21352. This function only applies to comment blocks, comments, example
  21353. blocks and paragraphs. Also, as a special case, re-align table
  21354. when point is at one.
  21355. If JUSTIFY is non-nil (interactively, with prefix argument),
  21356. justify as well. If `sentence-end-double-space' is non-nil, then
  21357. period followed by one space does not end a sentence, so don't
  21358. break a line there. The variable `fill-column' controls the
  21359. width for filling.
  21360. For convenience, when point is at a plain list, an item or
  21361. a footnote definition, try to fill the first paragraph within."
  21362. (interactive)
  21363. (if (and (derived-mode-p 'message-mode)
  21364. (or (not (message-in-body-p))
  21365. (save-excursion (move-beginning-of-line 1)
  21366. (looking-at message-cite-prefix-regexp))))
  21367. ;; First ensure filling is correct in message-mode.
  21368. (let ((fill-paragraph-function
  21369. (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
  21370. (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
  21371. (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
  21372. (paragraph-separate
  21373. (cadadr (assoc 'paragraph-separate org-fb-vars))))
  21374. (fill-paragraph nil))
  21375. (with-syntax-table org-mode-transpose-word-syntax-table
  21376. ;; Move to end of line in order to get the first paragraph
  21377. ;; within a plain list or a footnote definition.
  21378. (let ((element (save-excursion
  21379. (end-of-line)
  21380. (or (ignore-errors (org-element-at-point))
  21381. (user-error "An element cannot be parsed line %d"
  21382. (line-number-at-pos (point)))))))
  21383. ;; First check if point is in a blank line at the beginning of
  21384. ;; the buffer. In that case, ignore filling.
  21385. (case (org-element-type element)
  21386. ;; Use major mode filling function is src blocks.
  21387. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21388. ;; Align Org tables, leave table.el tables as-is.
  21389. (table-row (org-table-align) t)
  21390. (table
  21391. (when (eq (org-element-property :type element) 'org)
  21392. (save-excursion
  21393. (goto-char (org-element-property :post-affiliated element))
  21394. (org-table-align)))
  21395. t)
  21396. (paragraph
  21397. ;; Paragraphs may contain `line-break' type objects.
  21398. (let ((beg (max (point-min)
  21399. (org-element-property :contents-begin element)))
  21400. (end (min (point-max)
  21401. (org-element-property :contents-end element))))
  21402. ;; Do nothing if point is at an affiliated keyword.
  21403. (if (< (line-end-position) beg) t
  21404. (when (derived-mode-p 'message-mode)
  21405. ;; In `message-mode', do not fill following citation
  21406. ;; in current paragraph nor text before message body.
  21407. (let ((body-start (save-excursion (message-goto-body))))
  21408. (when body-start (setq beg (max body-start beg))))
  21409. (when (save-excursion
  21410. (re-search-forward
  21411. (concat "^" message-cite-prefix-regexp) end t))
  21412. (setq end (match-beginning 0))))
  21413. ;; Fill paragraph, taking line breaks into account.
  21414. (save-excursion
  21415. (goto-char beg)
  21416. (let ((cuts (list beg)))
  21417. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21418. (when (eq 'line-break
  21419. (org-element-type
  21420. (save-excursion (backward-char)
  21421. (org-element-context))))
  21422. (push (point) cuts)))
  21423. (dolist (c (delq end cuts))
  21424. (fill-region-as-paragraph c end justify)
  21425. (setq end c))))
  21426. t)))
  21427. ;; Contents of `comment-block' type elements should be
  21428. ;; filled as plain text, but only if point is within block
  21429. ;; markers.
  21430. (comment-block
  21431. (let* ((case-fold-search t)
  21432. (beg (save-excursion
  21433. (goto-char (org-element-property :begin element))
  21434. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21435. (forward-line)
  21436. (point)))
  21437. (end (save-excursion
  21438. (goto-char (org-element-property :end element))
  21439. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21440. (line-beginning-position))))
  21441. (if (or (< (point) beg) (> (point) end)) t
  21442. (fill-region-as-paragraph
  21443. (save-excursion (end-of-line)
  21444. (re-search-backward "^[ \t]*$" beg 'move)
  21445. (line-beginning-position))
  21446. (save-excursion (beginning-of-line)
  21447. (re-search-forward "^[ \t]*$" end 'move)
  21448. (line-beginning-position))
  21449. justify))))
  21450. ;; Fill comments.
  21451. (comment
  21452. (let ((begin (org-element-property :post-affiliated element))
  21453. (end (org-element-property :end element)))
  21454. (when (and (>= (point) begin) (<= (point) end))
  21455. (let ((begin (save-excursion
  21456. (end-of-line)
  21457. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21458. (progn (forward-line) (point))
  21459. begin)))
  21460. (end (save-excursion
  21461. (end-of-line)
  21462. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21463. (1- (line-beginning-position))
  21464. (skip-chars-backward " \r\t\n")
  21465. (line-end-position)))))
  21466. ;; Do not fill comments when at a blank line.
  21467. (when (> end begin)
  21468. (let ((fill-prefix
  21469. (save-excursion
  21470. (beginning-of-line)
  21471. (looking-at "[ \t]*#")
  21472. (let ((comment-prefix (match-string 0)))
  21473. (goto-char (match-end 0))
  21474. (if (looking-at adaptive-fill-regexp)
  21475. (concat comment-prefix (match-string 0))
  21476. (concat comment-prefix " "))))))
  21477. (save-excursion
  21478. (fill-region-as-paragraph begin end justify))))))
  21479. t))
  21480. ;; Ignore every other element.
  21481. (otherwise t))))))
  21482. (defun org-auto-fill-function ()
  21483. "Auto-fill function."
  21484. ;; Check if auto-filling is meaningful.
  21485. (let ((fc (current-fill-column)))
  21486. (when (and fc (> (current-column) fc))
  21487. (let* ((fill-prefix (org-adaptive-fill-function))
  21488. ;; Enforce empty fill prefix, if required. Otherwise, it
  21489. ;; will be computed again.
  21490. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21491. (when fill-prefix (do-auto-fill))))))
  21492. (defun org-comment-line-break-function (&optional soft)
  21493. "Break line at point and indent, continuing comment if within one.
  21494. The inserted newline is marked hard if variable
  21495. `use-hard-newlines' is true, unless optional argument SOFT is
  21496. non-nil."
  21497. (if soft (insert-and-inherit ?\n) (newline 1))
  21498. (save-excursion (forward-char -1) (delete-horizontal-space))
  21499. (delete-horizontal-space)
  21500. (indent-to-left-margin)
  21501. (insert-before-markers-and-inherit fill-prefix))
  21502. ;;; Fixed Width Areas
  21503. (defun org-toggle-fixed-width ()
  21504. "Toggle fixed-width markup.
  21505. Add or remove fixed-width markup on current line, whenever it
  21506. makes sense. Return an error otherwise.
  21507. If a region is active and if it contains only fixed-width areas
  21508. or blank lines, remove all fixed-width markup in it. If the
  21509. region contains anything else, convert all non-fixed-width lines
  21510. to fixed-width ones.
  21511. Blank lines at the end of the region are ignored unless the
  21512. region only contains such lines."
  21513. (interactive)
  21514. (if (not (org-region-active-p))
  21515. ;; No region:
  21516. ;;
  21517. ;; Remove fixed width marker only in a fixed-with element.
  21518. ;;
  21519. ;; Add fixed width maker in paragraphs, in blank lines after
  21520. ;; elements or at the beginning of a headline or an inlinetask,
  21521. ;; and before any one-line elements (e.g., a clock).
  21522. (progn
  21523. (beginning-of-line)
  21524. (let* ((element (org-element-at-point))
  21525. (type (org-element-type element)))
  21526. (cond
  21527. ((and (eq type 'fixed-width)
  21528. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21529. (replace-match
  21530. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21531. ((and (memq type '(babel-call clock comment diary-sexp headline
  21532. horizontal-rule keyword paragraph
  21533. planning))
  21534. (<= (org-element-property :post-affiliated element) (point)))
  21535. (skip-chars-forward " \t")
  21536. (insert ": "))
  21537. ((and (org-looking-at-p "[ \t]*$")
  21538. (or (eq type 'inlinetask)
  21539. (save-excursion
  21540. (skip-chars-forward " \r\t\n")
  21541. (<= (org-element-property :end element) (point)))))
  21542. (delete-region (point) (line-end-position))
  21543. (org-indent-line)
  21544. (insert ": "))
  21545. (t (user-error "Cannot insert a fixed-width line here")))))
  21546. ;; Region active.
  21547. (let* ((begin (save-excursion
  21548. (goto-char (region-beginning))
  21549. (line-beginning-position)))
  21550. (end (copy-marker
  21551. (save-excursion
  21552. (goto-char (region-end))
  21553. (unless (eolp) (beginning-of-line))
  21554. (if (save-excursion (re-search-backward "\\S-" begin t))
  21555. (progn (skip-chars-backward " \r\t\n") (point))
  21556. (point)))))
  21557. (all-fixed-width-p
  21558. (catch 'not-all-p
  21559. (save-excursion
  21560. (goto-char begin)
  21561. (skip-chars-forward " \r\t\n")
  21562. (when (eobp) (throw 'not-all-p nil))
  21563. (while (< (point) end)
  21564. (let ((element (org-element-at-point)))
  21565. (if (eq (org-element-type element) 'fixed-width)
  21566. (goto-char (org-element-property :end element))
  21567. (throw 'not-all-p nil))))
  21568. t))))
  21569. (if all-fixed-width-p
  21570. (save-excursion
  21571. (goto-char begin)
  21572. (while (< (point) end)
  21573. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21574. (replace-match
  21575. "" nil nil nil
  21576. (if (= (line-end-position) (match-end 0)) 0 1)))
  21577. (forward-line)))
  21578. (let ((min-ind (point-max)))
  21579. ;; Find minimum indentation across all lines.
  21580. (save-excursion
  21581. (goto-char begin)
  21582. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21583. (setq min-ind 0)
  21584. (catch 'zerop
  21585. (while (< (point) end)
  21586. (unless (org-looking-at-p "[ \t]*$")
  21587. (let ((ind (org-get-indentation)))
  21588. (setq min-ind (min min-ind ind))
  21589. (when (zerop ind) (throw 'zerop t))))
  21590. (forward-line)))))
  21591. ;; Loop over all lines and add fixed-width markup everywhere
  21592. ;; but in fixed-width lines.
  21593. (save-excursion
  21594. (goto-char begin)
  21595. (while (< (point) end)
  21596. (cond
  21597. ((org-at-heading-p)
  21598. (insert ": ")
  21599. (forward-line)
  21600. (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
  21601. (insert ":")
  21602. (forward-line)))
  21603. ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
  21604. (let* ((element (org-element-at-point))
  21605. (element-end (org-element-property :end element)))
  21606. (if (eq (org-element-type element) 'fixed-width)
  21607. (progn (goto-char element-end)
  21608. (skip-chars-backward " \r\t\n")
  21609. (forward-line))
  21610. (let ((limit (min end element-end)))
  21611. (while (< (point) limit)
  21612. (org-move-to-column min-ind t)
  21613. (insert ": ")
  21614. (forward-line))))))
  21615. (t
  21616. (org-move-to-column min-ind t)
  21617. (insert ": ")
  21618. (forward-line)))))))
  21619. (set-marker end nil))))
  21620. ;;; Comments
  21621. ;; Org comments syntax is quite complex. It requires the entire line
  21622. ;; to be just a comment. Also, even with the right syntax at the
  21623. ;; beginning of line, some some elements (i.e. verse-block or
  21624. ;; example-block) don't accept comments. Usual Emacs comment commands
  21625. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21626. ;; Org still relies on `comment-dwim', but cannot trust
  21627. ;; `comment-only-p'. So, `comment-region-function' and
  21628. ;; `uncomment-region-function' both point
  21629. ;; to`org-comment-or-uncomment-region'. Eventually,
  21630. ;; `org-insert-comment' takes care of insertion of comments at the
  21631. ;; beginning of line.
  21632. ;; `org-setup-comments-handling' install comments related variables
  21633. ;; during `org-mode' initialization.
  21634. (defun org-setup-comments-handling ()
  21635. (interactive)
  21636. (setq-local comment-use-syntax nil)
  21637. (setq-local comment-start "# ")
  21638. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21639. (setq-local comment-insert-comment-function 'org-insert-comment)
  21640. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21641. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21642. (defun org-insert-comment ()
  21643. "Insert an empty comment above current line.
  21644. If the line is empty, insert comment at its beginning. When
  21645. point is within a source block, comment according to the related
  21646. major mode."
  21647. (if (let ((element (org-element-at-point)))
  21648. (and (eq (org-element-type element) 'src-block)
  21649. (< (save-excursion
  21650. (goto-char (org-element-property :post-affiliated element))
  21651. (line-end-position))
  21652. (point))
  21653. (> (save-excursion
  21654. (goto-char (org-element-property :end element))
  21655. (skip-chars-backward " \r\t\n")
  21656. (line-beginning-position))
  21657. (point))))
  21658. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21659. (beginning-of-line)
  21660. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21661. (open-line 1))
  21662. (org-indent-line)
  21663. (insert "# ")))
  21664. (defvar comment-empty-lines) ; From newcomment.el.
  21665. (defun org-comment-or-uncomment-region (beg end &rest _)
  21666. "Comment or uncomment each non-blank line in the region.
  21667. Uncomment each non-blank line between BEG and END if it only
  21668. contains commented lines. Otherwise, comment them. If region is
  21669. strictly within a source block, use appropriate comment syntax."
  21670. (if (let ((element (org-element-at-point)))
  21671. (and (eq (org-element-type element) 'src-block)
  21672. (< (save-excursion
  21673. (goto-char (org-element-property :post-affiliated element))
  21674. (line-end-position))
  21675. beg)
  21676. (>= (save-excursion
  21677. (goto-char (org-element-property :end element))
  21678. (skip-chars-backward " \r\t\n")
  21679. (line-beginning-position))
  21680. end)))
  21681. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21682. (save-restriction
  21683. ;; Restrict region
  21684. (narrow-to-region (save-excursion (goto-char beg)
  21685. (skip-chars-forward " \r\t\n" end)
  21686. (line-beginning-position))
  21687. (save-excursion (goto-char end)
  21688. (skip-chars-backward " \r\t\n" beg)
  21689. (line-end-position)))
  21690. (let ((uncommentp
  21691. ;; UNCOMMENTP is non-nil when every non blank line between
  21692. ;; BEG and END is a comment.
  21693. (save-excursion
  21694. (goto-char (point-min))
  21695. (while (and (not (eobp))
  21696. (let ((element (org-element-at-point)))
  21697. (and (eq (org-element-type element) 'comment)
  21698. (goto-char (min (point-max)
  21699. (org-element-property
  21700. :end element)))))))
  21701. (eobp))))
  21702. (if uncommentp
  21703. ;; Only blank lines and comments in region: uncomment it.
  21704. (save-excursion
  21705. (goto-char (point-min))
  21706. (while (not (eobp))
  21707. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21708. (replace-match "" nil nil nil 1))
  21709. (forward-line)))
  21710. ;; Comment each line in region.
  21711. (let ((min-indent (point-max)))
  21712. ;; First find the minimum indentation across all lines.
  21713. (save-excursion
  21714. (goto-char (point-min))
  21715. (while (and (not (eobp)) (not (zerop min-indent)))
  21716. (unless (looking-at "[ \t]*$")
  21717. (setq min-indent (min min-indent (current-indentation))))
  21718. (forward-line)))
  21719. ;; Then loop over all lines.
  21720. (save-excursion
  21721. (goto-char (point-min))
  21722. (while (not (eobp))
  21723. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21724. ;; Don't get fooled by invisible text (e.g. link path)
  21725. ;; when moving to column MIN-INDENT.
  21726. (let ((buffer-invisibility-spec nil))
  21727. (org-move-to-column min-indent t))
  21728. (insert comment-start))
  21729. (forward-line)))))))))
  21730. (defun org-comment-dwim (_arg)
  21731. "Call `comment-dwim' within a source edit buffer if needed."
  21732. (interactive "*P")
  21733. (if (org-in-src-block-p)
  21734. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21735. (call-interactively 'comment-dwim)))
  21736. ;;; Timestamps API
  21737. ;; This section contains tools to operate on timestamp objects, as
  21738. ;; returned by, e.g. `org-element-context'.
  21739. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21740. "Encode TIMESTAMP object into Emacs internal time.
  21741. Use end of date range or time range when END is non-nil."
  21742. (apply #'encode-time
  21743. (cons 0
  21744. (mapcar
  21745. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21746. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21747. '(:minute-start :hour-start :day-start :month-start
  21748. :year-start))))))
  21749. (defun org-timestamp-has-time-p (timestamp)
  21750. "Non-nil when TIMESTAMP has a time specified."
  21751. (org-element-property :hour-start timestamp))
  21752. (defun org-timestamp-format (timestamp format &optional end utc)
  21753. "Format a TIMESTAMP object into a string.
  21754. FORMAT is a format specifier to be passed to
  21755. `format-time-string'.
  21756. When optional argument END is non-nil, use end of date-range or
  21757. time-range, if possible.
  21758. When optional argument UTC is non-nil, time will be expressed as
  21759. Universal Time."
  21760. (format-time-string
  21761. format (org-timestamp--to-internal-time timestamp end) utc))
  21762. (defun org-timestamp-split-range (timestamp &optional end)
  21763. "Extract a TIMESTAMP object from a date or time range.
  21764. END, when non-nil, means extract the end of the range.
  21765. Otherwise, extract its start.
  21766. Return a new timestamp object."
  21767. (let ((type (org-element-property :type timestamp)))
  21768. (if (memq type '(active inactive diary)) timestamp
  21769. (let ((split-ts (org-element-copy timestamp)))
  21770. ;; Set new type.
  21771. (org-element-put-property
  21772. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21773. ;; Copy start properties over end properties if END is
  21774. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21775. (let ((p-alist '((:minute-start . :minute-end)
  21776. (:hour-start . :hour-end)
  21777. (:day-start . :day-end)
  21778. (:month-start . :month-end)
  21779. (:year-start . :year-end))))
  21780. (dolist (p-cell p-alist)
  21781. (org-element-put-property
  21782. split-ts
  21783. (funcall (if end #'car #'cdr) p-cell)
  21784. (org-element-property
  21785. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21786. ;; Eventually refresh `:raw-value'.
  21787. (org-element-put-property split-ts :raw-value nil)
  21788. (org-element-put-property
  21789. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21790. (defun org-timestamp-translate (timestamp &optional boundary)
  21791. "Translate TIMESTAMP object to custom format.
  21792. Format string is defined in `org-time-stamp-custom-formats',
  21793. which see.
  21794. When optional argument BOUNDARY is non-nil, it is either the
  21795. symbol `start' or `end'. In this case, only translate the
  21796. starting or ending part of TIMESTAMP if it is a date or time
  21797. range. Otherwise, translate both parts.
  21798. Return timestamp as-is if `org-display-custom-times' is nil or if
  21799. it has a `diary' type."
  21800. (let ((type (org-element-property :type timestamp)))
  21801. (if (or (not org-display-custom-times) (eq type 'diary))
  21802. (org-element-interpret-data timestamp)
  21803. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21804. org-time-stamp-custom-formats)))
  21805. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21806. (concat (org-timestamp-format timestamp fmt)
  21807. "--"
  21808. (org-timestamp-format timestamp fmt t))
  21809. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21810. ;;; Other stuff.
  21811. (defvar reftex-docstruct-symbol)
  21812. (defvar reftex-cite-format)
  21813. (defvar org--rds)
  21814. (defun org-reftex-citation ()
  21815. "Use reftex-citation to insert a citation into the buffer.
  21816. This looks for a line like
  21817. #+BIBLIOGRAPHY: foo plain option:-d
  21818. and derives from it that foo.bib is the bibliography file relevant
  21819. for this document. It then installs the necessary environment for RefTeX
  21820. to work in this buffer and calls `reftex-citation' to insert a citation
  21821. into the buffer.
  21822. Export of such citations to both LaTeX and HTML is handled by the contributed
  21823. package ox-bibtex by Taru Karttunen."
  21824. (interactive)
  21825. (let ((reftex-docstruct-symbol 'org--rds)
  21826. (reftex-cite-format "\\cite{%l}")
  21827. org--rds bib)
  21828. (save-excursion
  21829. (save-restriction
  21830. (widen)
  21831. (let ((case-fold-search t)
  21832. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21833. (if (not (save-excursion
  21834. (or (re-search-forward re nil t)
  21835. (re-search-backward re nil t))))
  21836. (user-error "No bibliography defined in file")
  21837. (setq bib (concat (match-string 1) ".bib")
  21838. org--rds (list (list 'bib bib)))))))
  21839. (call-interactively 'reftex-citation)))
  21840. ;;;; Functions extending outline functionality
  21841. (defun org-beginning-of-line (&optional arg)
  21842. "Go to the beginning of the current line. If that is invisible, continue
  21843. to a visible line beginning. This makes the function of C-a more intuitive.
  21844. If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
  21845. first attempt, and only move to after the tags when the cursor is already
  21846. beyond the end of the headline."
  21847. (interactive "P")
  21848. (let ((pos (point))
  21849. (special (if (consp org-special-ctrl-a/e)
  21850. (car org-special-ctrl-a/e)
  21851. org-special-ctrl-a/e))
  21852. deactivate-mark refpos)
  21853. (if (org-bound-and-true-p visual-line-mode)
  21854. (beginning-of-visual-line 1)
  21855. (beginning-of-line 1))
  21856. (if (and arg (fboundp 'move-beginning-of-line))
  21857. (call-interactively 'move-beginning-of-line)
  21858. (unless (bobp)
  21859. (backward-char 1)
  21860. (if (org-truely-invisible-p)
  21861. (while (and (not (bobp)) (org-truely-invisible-p))
  21862. (backward-char 1)
  21863. (beginning-of-line 1))
  21864. (forward-char 1))))
  21865. (when special
  21866. (cond
  21867. ((and (looking-at org-complex-heading-regexp)
  21868. (eq (char-after (match-end 1)) ?\s))
  21869. (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21870. (point-at-eol)))
  21871. (goto-char
  21872. (if (eq special t)
  21873. (cond ((> pos refpos) refpos)
  21874. ((= pos (point)) refpos)
  21875. (t (point)))
  21876. (cond ((> pos (point)) (point))
  21877. ((not (eq last-command this-command)) (point))
  21878. (t refpos)))))
  21879. ((org-at-item-p)
  21880. ;; Being at an item and not looking at an the item means point
  21881. ;; was previously moved to beginning of a visual line, which
  21882. ;; doesn't contain the item. Therefore, do nothing special,
  21883. ;; just stay here.
  21884. (when (looking-at org-list-full-item-re)
  21885. ;; Set special position at first white space character after
  21886. ;; bullet, and check-box, if any.
  21887. (let ((after-bullet
  21888. (let ((box (match-end 3)))
  21889. (if (not box) (match-end 1)
  21890. (let ((after (char-after box)))
  21891. (if (and after (= after ? )) (1+ box) box))))))
  21892. ;; Special case: Move point to special position when
  21893. ;; currently after it or at beginning of line.
  21894. (if (eq special t)
  21895. (when (or (> pos after-bullet) (= (point) pos))
  21896. (goto-char after-bullet))
  21897. ;; Reversed case: Move point to special position when
  21898. ;; point was already at beginning of line and command is
  21899. ;; repeated.
  21900. (when (and (= (point) pos) (eq last-command this-command))
  21901. (goto-char after-bullet))))))))
  21902. (org-no-warnings
  21903. (and (featurep 'xemacs) (setq zmacs-region-stays t))))
  21904. (setq disable-point-adjustment
  21905. (or (not (invisible-p (point)))
  21906. (not (invisible-p (max (point-min) (1- (point))))))))
  21907. (defun org-end-of-line (&optional arg)
  21908. "Go to the end of the line.
  21909. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21910. tags on the first attempt, and only move to after the tags when
  21911. the cursor is already beyond the end of the headline."
  21912. (interactive "P")
  21913. (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
  21914. org-special-ctrl-a/e))
  21915. (move-fun (cond ((org-bound-and-true-p visual-line-mode)
  21916. 'end-of-visual-line)
  21917. ((fboundp 'move-end-of-line) 'move-end-of-line)
  21918. (t 'end-of-line)))
  21919. deactivate-mark)
  21920. (if (or (not special) arg) (call-interactively move-fun)
  21921. (let* ((element (save-excursion (beginning-of-line)
  21922. (org-element-at-point)))
  21923. (type (org-element-type element)))
  21924. (cond
  21925. ((memq type '(headline inlinetask))
  21926. (let ((pos (point)))
  21927. (beginning-of-line 1)
  21928. (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
  21929. (if (eq special t)
  21930. (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
  21931. (goto-char (match-beginning 1))
  21932. (goto-char (match-end 0)))
  21933. (if (or (< pos (match-end 0))
  21934. (not (eq this-command last-command)))
  21935. (goto-char (match-end 0))
  21936. (goto-char (match-beginning 1))))
  21937. (call-interactively move-fun))))
  21938. ((outline-invisible-p (line-end-position))
  21939. ;; If element is hidden, `move-end-of-line' would put point
  21940. ;; after it. Use `end-of-line' to stay on current line.
  21941. (call-interactively 'end-of-line))
  21942. (t (call-interactively move-fun)))))
  21943. (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
  21944. (setq disable-point-adjustment
  21945. (or (not (invisible-p (point)))
  21946. (not (invisible-p (max (point-min) (1- (point))))))))
  21947. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21948. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21949. (defun org-backward-sentence (&optional _arg)
  21950. "Go to beginning of sentence, or beginning of table field.
  21951. This will call `backward-sentence' or `org-table-beginning-of-field',
  21952. depending on context."
  21953. (interactive)
  21954. (let* ((element (org-element-at-point))
  21955. (contents-begin (org-element-property :contents-begin element))
  21956. (table (org-element-lineage element '(table) t)))
  21957. (if (and table
  21958. (> (point) contents-begin)
  21959. (<= (point) (org-element-property :contents-end table)))
  21960. (call-interactively #'org-table-beginning-of-field)
  21961. (save-restriction
  21962. (when (and contents-begin
  21963. (< (point-min) contents-begin)
  21964. (> (point) contents-begin))
  21965. (narrow-to-region contents-begin
  21966. (org-element-property :contents-end element)))
  21967. (call-interactively #'backward-sentence)))))
  21968. (defun org-forward-sentence (&optional _arg)
  21969. "Go to end of sentence, or end of table field.
  21970. This will call `forward-sentence' or `org-table-end-of-field',
  21971. depending on context."
  21972. (interactive)
  21973. (let* ((element (org-element-at-point))
  21974. (contents-end (org-element-property :contents-end element))
  21975. (table (org-element-lineage element '(table) t)))
  21976. (if (and table
  21977. (>= (point) (org-element-property :contents-begin table))
  21978. (< (point) contents-end))
  21979. (call-interactively #'org-table-end-of-field)
  21980. (save-restriction
  21981. (when (and contents-end
  21982. (> (point-max) contents-end)
  21983. ;; Skip blank lines between elements.
  21984. (< (org-element-property :end element)
  21985. (save-excursion (goto-char contents-end)
  21986. (skip-chars-forward " \r\t\n"))))
  21987. (narrow-to-region (org-element-property :contents-begin element)
  21988. contents-end))
  21989. (call-interactively #'forward-sentence)))))
  21990. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21991. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21992. (defun org-kill-line (&optional _arg)
  21993. "Kill line, to tags or end of line."
  21994. (interactive)
  21995. (cond
  21996. ((or (not org-special-ctrl-k)
  21997. (bolp)
  21998. (not (org-at-heading-p)))
  21999. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  22000. org-ctrl-k-protect-subtree
  22001. (or (eq org-ctrl-k-protect-subtree 'error)
  22002. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  22003. (user-error "C-k aborted as it would kill a hidden subtree"))
  22004. (call-interactively
  22005. (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  22006. ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
  22007. (kill-region (point) (match-beginning 1))
  22008. (org-set-tags nil t))
  22009. (t (kill-region (point) (point-at-eol)))))
  22010. (define-key org-mode-map "\C-k" 'org-kill-line)
  22011. (defun org-yank (&optional arg)
  22012. "Yank. If the kill is a subtree, treat it specially.
  22013. This command will look at the current kill and check if is a single
  22014. subtree, or a series of subtrees[1]. If it passes the test, and if the
  22015. cursor is at the beginning of a line or after the stars of a currently
  22016. empty headline, then the yank is handled specially. How exactly depends
  22017. on the value of the following variables, both set by default.
  22018. `org-yank-folded-subtrees'
  22019. When set, the subtree(s) will be folded after insertion, but only
  22020. if doing so would now swallow text after the yanked text.
  22021. `org-yank-adjusted-subtrees'
  22022. When set, the subtree will be promoted or demoted in order to
  22023. fit into the local outline tree structure, which means that the
  22024. level will be adjusted so that it becomes the smaller one of the
  22025. two *visible* surrounding headings.
  22026. Any prefix to this command will cause `yank' to be called directly with
  22027. no special treatment. In particular, a simple \\[universal-argument] prefix \
  22028. will just
  22029. plainly yank the text as it is.
  22030. \[1] The test checks if the first non-white line is a heading
  22031. and if there are no other headings with fewer stars."
  22032. (interactive "P")
  22033. (org-yank-generic 'yank arg))
  22034. (defun org-yank-generic (command arg)
  22035. "Perform some yank-like command.
  22036. This function implements the behavior described in the `org-yank'
  22037. documentation. However, it has been generalized to work for any
  22038. interactive command with similar behavior."
  22039. ;; pretend to be command COMMAND
  22040. (setq this-command command)
  22041. (if arg
  22042. (call-interactively command)
  22043. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  22044. (and (org-kill-is-subtree-p)
  22045. (or (bolp)
  22046. (and (looking-at "[ \t]*$")
  22047. (string-match
  22048. "\\`\\*+\\'"
  22049. (buffer-substring (point-at-bol) (point)))))))
  22050. swallowp)
  22051. (cond
  22052. ((and subtreep org-yank-folded-subtrees)
  22053. (let ((beg (point))
  22054. end)
  22055. (if (and subtreep org-yank-adjusted-subtrees)
  22056. (org-paste-subtree nil nil 'for-yank)
  22057. (call-interactively command))
  22058. (setq end (point))
  22059. (goto-char beg)
  22060. (when (and (bolp) subtreep
  22061. (not (setq swallowp
  22062. (org-yank-folding-would-swallow-text beg end))))
  22063. (org-with-limited-levels
  22064. (or (looking-at org-outline-regexp)
  22065. (re-search-forward org-outline-regexp-bol end t))
  22066. (while (and (< (point) end) (looking-at org-outline-regexp))
  22067. (outline-hide-subtree)
  22068. (org-cycle-show-empty-lines 'folded)
  22069. (condition-case nil
  22070. (outline-forward-same-level 1)
  22071. (error (goto-char end))))))
  22072. (when swallowp
  22073. (message
  22074. "Inserted text not folded because that would swallow text"))
  22075. (goto-char end)
  22076. (skip-chars-forward " \t\n\r")
  22077. (beginning-of-line 1)
  22078. (push-mark beg 'nomsg)))
  22079. ((and subtreep org-yank-adjusted-subtrees)
  22080. (let ((beg (point-at-bol)))
  22081. (org-paste-subtree nil nil 'for-yank)
  22082. (push-mark beg 'nomsg)))
  22083. (t
  22084. (call-interactively command))))))
  22085. (defun org-yank-folding-would-swallow-text (beg end)
  22086. "Would hide-subtree at BEG swallow any text after END?"
  22087. (let (level)
  22088. (org-with-limited-levels
  22089. (save-excursion
  22090. (goto-char beg)
  22091. (when (or (looking-at org-outline-regexp)
  22092. (re-search-forward org-outline-regexp-bol end t))
  22093. (setq level (org-outline-level)))
  22094. (goto-char end)
  22095. (skip-chars-forward " \t\r\n\v\f")
  22096. (not (or (eobp)
  22097. (and (bolp) (looking-at-p org-outline-regexp)
  22098. (<= (org-outline-level) level))))))))
  22099. (define-key org-mode-map "\C-y" 'org-yank)
  22100. (defun org-truely-invisible-p ()
  22101. "Check if point is at a character currently not visible.
  22102. This version does not only check the character property, but also
  22103. `visible-mode'."
  22104. ;; Early versions of noutline don't have `outline-invisible-p'.
  22105. (unless (org-bound-and-true-p visible-mode)
  22106. (outline-invisible-p)))
  22107. (defun org-invisible-p2 ()
  22108. "Check if point is at a character currently not visible."
  22109. (save-excursion
  22110. (when (and (eolp) (not (bobp))) (backward-char 1))
  22111. ;; Early versions of noutline don't have `outline-invisible-p'.
  22112. (outline-invisible-p)))
  22113. (defun org-back-to-heading (&optional invisible-ok)
  22114. "Call `outline-back-to-heading', but provide a better error message."
  22115. (condition-case nil
  22116. (outline-back-to-heading invisible-ok)
  22117. (error (error "Before first headline at position %d in buffer %s"
  22118. (point) (current-buffer)))))
  22119. (defun org-before-first-heading-p ()
  22120. "Before first heading?"
  22121. (save-excursion
  22122. (end-of-line)
  22123. (null (re-search-backward org-outline-regexp-bol nil t))))
  22124. (defun org-at-heading-p (&optional ignored)
  22125. (outline-on-heading-p t))
  22126. ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
  22127. ;;; warning was only added in Org 9.0, which should be taken into
  22128. ;;; account when deciding when to remove the alias.
  22129. (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
  22130. (defun org-in-commented-heading-p (&optional no-inheritance)
  22131. "Non-nil if point is under a commented heading.
  22132. This function also checks ancestors of the current headline,
  22133. unless optional argument NO-INHERITANCE is non-nil."
  22134. (cond
  22135. ((org-before-first-heading-p) nil)
  22136. ((let ((headline (nth 4 (org-heading-components))))
  22137. (and headline
  22138. (let ((case-fold-search nil))
  22139. (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22140. headline)))))
  22141. (no-inheritance nil)
  22142. (t
  22143. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22144. (defun org-at-comment-p nil
  22145. "Is cursor in a commented line?"
  22146. (save-excursion
  22147. (save-match-data
  22148. (beginning-of-line)
  22149. (looking-at "^[ \t]*# "))))
  22150. (defun org-at-drawer-p nil
  22151. "Is cursor at a drawer keyword?"
  22152. (save-excursion
  22153. (move-beginning-of-line 1)
  22154. (looking-at org-drawer-regexp)))
  22155. (defun org-at-block-p nil
  22156. "Is cursor at a block keyword?"
  22157. (save-excursion
  22158. (move-beginning-of-line 1)
  22159. (looking-at org-block-regexp)))
  22160. (defun org-point-at-end-of-empty-headline ()
  22161. "If point is at the end of an empty headline, return t, else nil.
  22162. If the heading only contains a TODO keyword, it is still still considered
  22163. empty."
  22164. (and (looking-at "[ \t]*$")
  22165. (when org-todo-line-regexp
  22166. (save-excursion
  22167. (beginning-of-line 1)
  22168. (let ((case-fold-search nil))
  22169. (looking-at org-todo-line-regexp)
  22170. (string= (match-string 3) ""))))))
  22171. (defun org-at-heading-or-item-p ()
  22172. (or (org-at-heading-p) (org-at-item-p)))
  22173. (defun org-at-target-p ()
  22174. (or (org-in-regexp org-radio-target-regexp)
  22175. (org-in-regexp org-target-regexp)))
  22176. ;; Compatibility alias with Org versions < 7.8.03
  22177. (defalias 'org-on-target-p 'org-at-target-p)
  22178. (defun org-up-heading-all (arg)
  22179. "Move to the heading line of which the present line is a subheading.
  22180. This function considers both visible and invisible heading lines.
  22181. With argument, move up ARG levels."
  22182. (if (fboundp 'outline-up-heading-all)
  22183. (outline-up-heading-all arg) ; emacs 21 version of outline.el
  22184. (outline-up-heading arg t))) ; emacs 22 version of outline.el
  22185. (defun org-up-heading-safe ()
  22186. "Move to the heading line of which the present line is a subheading.
  22187. This version will not throw an error. It will return the level of the
  22188. headline found, or nil if no higher level is found.
  22189. Also, this function will be a lot faster than `outline-up-heading',
  22190. because it relies on stars being the outline starters. This can really
  22191. make a significant difference in outlines with very many siblings."
  22192. (when (ignore-errors (org-back-to-heading t))
  22193. (let ((level-up (1- (funcall outline-level))))
  22194. (and (> level-up 0)
  22195. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22196. (funcall outline-level)))))
  22197. (defun org-first-sibling-p ()
  22198. "Is this heading the first child of its parents?"
  22199. (interactive)
  22200. (let ((re org-outline-regexp-bol)
  22201. level l)
  22202. (unless (org-at-heading-p t)
  22203. (user-error "Not at a heading"))
  22204. (setq level (funcall outline-level))
  22205. (save-excursion
  22206. (if (not (re-search-backward re nil t))
  22207. t
  22208. (setq l (funcall outline-level))
  22209. (< l level)))))
  22210. (defun org-goto-sibling (&optional previous)
  22211. "Goto the next sibling, even if it is invisible.
  22212. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22213. when a sibling was found. When none is found, return nil and don't
  22214. move point."
  22215. (let ((fun (if previous 're-search-backward 're-search-forward))
  22216. (pos (point))
  22217. (re org-outline-regexp-bol)
  22218. level l)
  22219. (when (ignore-errors (org-back-to-heading t))
  22220. (setq level (funcall outline-level))
  22221. (catch 'exit
  22222. (or previous (forward-char 1))
  22223. (while (funcall fun re nil t)
  22224. (setq l (funcall outline-level))
  22225. (when (< l level) (goto-char pos) (throw 'exit nil))
  22226. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22227. (goto-char pos)
  22228. nil))))
  22229. (defun org-show-siblings ()
  22230. "Show all siblings of the current headline."
  22231. (save-excursion
  22232. (while (org-goto-sibling) (org-flag-heading nil)))
  22233. (save-excursion
  22234. (while (org-goto-sibling 'previous)
  22235. (org-flag-heading nil))))
  22236. (defun org-goto-first-child ()
  22237. "Goto the first child, even if it is invisible.
  22238. Return t when a child was found. Otherwise don't move point and
  22239. return nil."
  22240. (let (level (pos (point)) (re org-outline-regexp-bol))
  22241. (when (ignore-errors (org-back-to-heading t))
  22242. (setq level (outline-level))
  22243. (forward-char 1)
  22244. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22245. (progn (goto-char (match-beginning 0)) t)
  22246. (goto-char pos) nil))))
  22247. (defun org-show-hidden-entry ()
  22248. "Show an entry where even the heading is hidden."
  22249. (save-excursion
  22250. (org-show-entry)))
  22251. (defun org-flag-heading (flag &optional entry)
  22252. "Flag the current heading. FLAG non-nil means make invisible.
  22253. When ENTRY is non-nil, show the entire entry."
  22254. (save-excursion
  22255. (org-back-to-heading t)
  22256. ;; Check if we should show the entire entry
  22257. (if entry
  22258. (progn
  22259. (org-show-entry)
  22260. (save-excursion
  22261. (and (outline-next-heading)
  22262. (org-flag-heading nil))))
  22263. (outline-flag-region (max (point-min) (1- (point)))
  22264. (save-excursion (outline-end-of-heading) (point))
  22265. flag))))
  22266. (defun org-get-next-sibling ()
  22267. "Move to next heading of the same level, and return point.
  22268. If there is no such heading, return nil.
  22269. This is like outline-next-sibling, but invisible headings are ok."
  22270. (let ((level (funcall outline-level)))
  22271. (outline-next-heading)
  22272. (while (and (not (eobp)) (> (funcall outline-level) level))
  22273. (outline-next-heading))
  22274. (unless (or (eobp) (< (funcall outline-level) level))
  22275. (point))))
  22276. (defun org-get-last-sibling ()
  22277. "Move to previous heading of the same level, and return point.
  22278. If there is no such heading, return nil."
  22279. (let ((opoint (point))
  22280. (level (funcall outline-level)))
  22281. (outline-previous-heading)
  22282. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22283. (while (and (> (funcall outline-level) level)
  22284. (not (bobp)))
  22285. (outline-previous-heading))
  22286. (unless (< (funcall outline-level) level)
  22287. (point)))))
  22288. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22289. "Goto to the end of a subtree."
  22290. ;; This contains an exact copy of the original function, but it uses
  22291. ;; `org-back-to-heading', to make it work also in invisible
  22292. ;; trees. And is uses an invisible-ok argument.
  22293. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22294. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22295. ;; with many children and grandchildren etc, this can be much faster
  22296. ;; than the outline version.
  22297. (org-back-to-heading invisible-ok)
  22298. (let ((first t)
  22299. (level (funcall outline-level)))
  22300. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22301. ;; A true heading (not a plain list item), in Org-mode
  22302. ;; This means we can easily find the end by looking
  22303. ;; only for the right number of stars. Using a regexp to do
  22304. ;; this is so much faster than using a Lisp loop.
  22305. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22306. (forward-char 1)
  22307. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22308. ;; something else, do it the slow way
  22309. (while (and (not (eobp))
  22310. (or first (> (funcall outline-level) level)))
  22311. (setq first nil)
  22312. (outline-next-heading)))
  22313. (unless to-heading
  22314. (when (memq (preceding-char) '(?\n ?\^M))
  22315. ;; Go to end of line before heading
  22316. (forward-char -1)
  22317. (when (memq (preceding-char) '(?\n ?\^M))
  22318. ;; leave blank line before heading
  22319. (forward-char -1)))))
  22320. (point))
  22321. (defun org-end-of-meta-data (&optional full)
  22322. "Skip planning line and properties drawer in current entry.
  22323. When optional argument FULL is non-nil, also skip empty lines,
  22324. clocking lines and regular drawers at the beginning of the
  22325. entry."
  22326. (org-back-to-heading t)
  22327. (forward-line)
  22328. (when (org-looking-at-p org-planning-line-re) (forward-line))
  22329. (when (looking-at org-property-drawer-re)
  22330. (goto-char (match-end 0))
  22331. (forward-line))
  22332. (when (and full (not (org-at-heading-p)))
  22333. (catch 'exit
  22334. (let ((end (save-excursion (outline-next-heading) (point)))
  22335. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22336. (while (not (eobp))
  22337. (cond ((org-looking-at-p org-drawer-regexp)
  22338. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22339. (forward-line)
  22340. (throw 'exit t)))
  22341. ((org-looking-at-p re) (forward-line))
  22342. (t (throw 'exit t))))))))
  22343. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22344. "Move forward to the ARG'th subheading at same level as this one.
  22345. Stop at the first and last subheadings of a superior heading.
  22346. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22347. non-nil it will also look at invisible ones."
  22348. (interactive "p")
  22349. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22350. (if (and arg (< arg 0))
  22351. (goto-char (point-min))
  22352. (outline-next-heading))
  22353. (org-at-heading-p)
  22354. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22355. (f (if (and arg (< arg 0))
  22356. 're-search-backward
  22357. 're-search-forward))
  22358. (count (if arg (abs arg) 1))
  22359. (result (point)))
  22360. (while (and (prog1 (> count 0)
  22361. (forward-char (if (and arg (< arg 0)) -1 1)))
  22362. (funcall f org-outline-regexp-bol nil 'move))
  22363. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22364. (cond ((< l level) (setq count 0))
  22365. ((and (= l level)
  22366. (or invisible-ok
  22367. (progn
  22368. (goto-char (line-beginning-position))
  22369. (not (outline-invisible-p)))))
  22370. (setq count (1- count))
  22371. (when (eq l level)
  22372. (setq result (point)))))))
  22373. (goto-char result))
  22374. (beginning-of-line 1)))
  22375. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22376. "Move backward to the ARG'th subheading at same level as this one.
  22377. Stop at the first and last subheadings of a superior heading."
  22378. (interactive "p")
  22379. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22380. (defun org-next-visible-heading (arg)
  22381. "Move to the next visible heading.
  22382. This function wraps `outline-next-visible-heading' with
  22383. `org-with-limited-levels' in order to skip over inline tasks and
  22384. respect customization of `org-odd-levels-only'."
  22385. (interactive "p")
  22386. (org-with-limited-levels
  22387. (outline-next-visible-heading arg)))
  22388. (defun org-previous-visible-heading (arg)
  22389. "Move to the next visible heading.
  22390. This function wraps `outline-previous-visible-heading' with
  22391. `org-with-limited-levels' in order to skip over inline tasks and
  22392. respect customization of `org-odd-levels-only'."
  22393. (interactive "p")
  22394. (org-with-limited-levels
  22395. (outline-previous-visible-heading arg)))
  22396. (defun org-next-block (arg &optional backward block-regexp)
  22397. "Jump to the next block.
  22398. With a prefix argument ARG, jump forward ARG many blocks.
  22399. When BACKWARD is non-nil, jump to the previous block.
  22400. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22401. Match data is set according to this regexp when the function
  22402. returns.
  22403. Return point at beginning of the opening line of found block.
  22404. Throw an error if no block is found."
  22405. (interactive "p")
  22406. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22407. (case-fold-search t)
  22408. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22409. (count (or arg 1))
  22410. (origin (point))
  22411. last-element)
  22412. (if backward (beginning-of-line) (end-of-line))
  22413. (while (and (> count 0) (funcall search-fn re nil t))
  22414. (let ((element (save-excursion
  22415. (goto-char (match-beginning 0))
  22416. (save-match-data (org-element-at-point)))))
  22417. (when (and (memq (org-element-type element)
  22418. '(center-block comment-block dynamic-block
  22419. example-block export-block quote-block
  22420. special-block src-block verse-block))
  22421. (<= (match-beginning 0)
  22422. (org-element-property :post-affiliated element)))
  22423. (setq last-element element)
  22424. (decf count))))
  22425. (if (= count 0)
  22426. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22427. (save-match-data (org-show-context)))
  22428. (goto-char origin)
  22429. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22430. (defun org-previous-block (arg &optional block-regexp)
  22431. "Jump to the previous block.
  22432. With a prefix argument ARG, jump backward ARG many source blocks.
  22433. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22434. (interactive "p")
  22435. (org-next-block arg t block-regexp))
  22436. (defun org-forward-paragraph ()
  22437. "Move forward to beginning of next paragraph or equivalent.
  22438. The function moves point to the beginning of the next visible
  22439. structural element, which can be a paragraph, a table, a list
  22440. item, etc. It also provides some special moves for convenience:
  22441. - On an affiliated keyword, jump to the beginning of the
  22442. relative element.
  22443. - On an item or a footnote definition, move to the second
  22444. element inside, if any.
  22445. - On a table or a property drawer, jump after it.
  22446. - On a verse or source block, stop after blank lines."
  22447. (interactive)
  22448. (when (eobp) (user-error "Cannot move further down"))
  22449. (let* ((deactivate-mark nil)
  22450. (element (org-element-at-point))
  22451. (type (org-element-type element))
  22452. (post-affiliated (org-element-property :post-affiliated element))
  22453. (contents-begin (org-element-property :contents-begin element))
  22454. (contents-end (org-element-property :contents-end element))
  22455. (end (let ((end (org-element-property :end element)) (parent element))
  22456. (while (and (setq parent (org-element-property :parent parent))
  22457. (= (org-element-property :contents-end parent) end))
  22458. (setq end (org-element-property :end parent)))
  22459. end)))
  22460. (cond ((not element)
  22461. (skip-chars-forward " \r\t\n")
  22462. (or (eobp) (beginning-of-line)))
  22463. ;; On affiliated keywords, move to element's beginning.
  22464. ((< (point) post-affiliated)
  22465. (goto-char post-affiliated))
  22466. ;; At a table row, move to the end of the table. Similarly,
  22467. ;; at a node property, move to the end of the property
  22468. ;; drawer.
  22469. ((memq type '(node-property table-row))
  22470. (goto-char (org-element-property
  22471. :end (org-element-property :parent element))))
  22472. ((memq type '(property-drawer table)) (goto-char end))
  22473. ;; Consider blank lines as separators in verse and source
  22474. ;; blocks to ease editing.
  22475. ((memq type '(src-block verse-block))
  22476. (when (eq type 'src-block)
  22477. (setq contents-end
  22478. (save-excursion (goto-char end)
  22479. (skip-chars-backward " \r\t\n")
  22480. (line-beginning-position))))
  22481. (beginning-of-line)
  22482. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22483. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22484. (goto-char end)
  22485. (skip-chars-forward " \r\t\n")
  22486. (if (= (point) contents-end) (goto-char end)
  22487. (beginning-of-line))))
  22488. ;; With no contents, just skip element.
  22489. ((not contents-begin) (goto-char end))
  22490. ;; If contents are invisible, skip the element altogether.
  22491. ((outline-invisible-p (line-end-position))
  22492. (case type
  22493. (headline
  22494. (org-with-limited-levels (outline-next-visible-heading 1)))
  22495. ;; At a plain list, make sure we move to the next item
  22496. ;; instead of skipping the whole list.
  22497. (plain-list (forward-char)
  22498. (org-forward-paragraph))
  22499. (otherwise (goto-char end))))
  22500. ((>= (point) contents-end) (goto-char end))
  22501. ((>= (point) contents-begin)
  22502. ;; This can only happen on paragraphs and plain lists.
  22503. (case type
  22504. (paragraph (goto-char end))
  22505. ;; At a plain list, try to move to second element in
  22506. ;; first item, if possible.
  22507. (plain-list (end-of-line)
  22508. (org-forward-paragraph))))
  22509. ;; When contents start on the middle of a line (e.g. in
  22510. ;; items and footnote definitions), try to reach first
  22511. ;; element starting after current line.
  22512. ((> (line-end-position) contents-begin)
  22513. (end-of-line)
  22514. (org-forward-paragraph))
  22515. (t (goto-char contents-begin)))))
  22516. (defun org-backward-paragraph ()
  22517. "Move backward to start of previous paragraph or equivalent.
  22518. The function moves point to the beginning of the current
  22519. structural element, which can be a paragraph, a table, a list
  22520. item, etc., or to the beginning of the previous visible one if
  22521. point is already there. It also provides some special moves for
  22522. convenience:
  22523. - On an affiliated keyword, jump to the first one.
  22524. - On a table or a property drawer, move to its beginning.
  22525. - On a verse or source block, stop before blank lines."
  22526. (interactive)
  22527. (when (bobp) (user-error "Cannot move further up"))
  22528. (let* ((deactivate-mark nil)
  22529. (element (org-element-at-point))
  22530. (type (org-element-type element))
  22531. (contents-begin (org-element-property :contents-begin element))
  22532. (contents-end (org-element-property :contents-end element))
  22533. (post-affiliated (org-element-property :post-affiliated element))
  22534. (begin (org-element-property :begin element)))
  22535. (cond
  22536. ((not element) (goto-char (point-min)))
  22537. ((= (point) begin)
  22538. (backward-char)
  22539. (org-backward-paragraph))
  22540. ((<= (point) post-affiliated) (goto-char begin))
  22541. ((memq type '(node-property table-row))
  22542. (goto-char (org-element-property
  22543. :post-affiliated (org-element-property :parent element))))
  22544. ((memq type '(property-drawer table)) (goto-char begin))
  22545. ((memq type '(src-block verse-block))
  22546. (when (eq type 'src-block)
  22547. (setq contents-begin
  22548. (save-excursion (goto-char begin) (forward-line) (point))))
  22549. (if (= (point) contents-begin) (goto-char post-affiliated)
  22550. ;; Inside a verse block, see blank lines as paragraph
  22551. ;; separators.
  22552. (let ((origin (point)))
  22553. (skip-chars-backward " \r\t\n" contents-begin)
  22554. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22555. (skip-chars-forward " \r\t\n" origin)
  22556. (if (= (point) origin) (goto-char contents-begin)
  22557. (beginning-of-line))))))
  22558. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22559. ((eq type 'paragraph)
  22560. (goto-char contents-begin)
  22561. ;; When at first paragraph in an item or a footnote definition,
  22562. ;; move directly to beginning of line.
  22563. (let ((parent-contents
  22564. (org-element-property
  22565. :contents-begin (org-element-property :parent element))))
  22566. (when (and parent-contents (= parent-contents contents-begin))
  22567. (beginning-of-line))))
  22568. ;; At the end of a greater element, move to the beginning of the
  22569. ;; last element within.
  22570. ((>= (point) contents-end)
  22571. (goto-char (1- contents-end))
  22572. (org-backward-paragraph))
  22573. (t (goto-char (or post-affiliated begin))))
  22574. ;; Ensure we never leave point invisible.
  22575. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22576. (defun org-forward-element ()
  22577. "Move forward by one element.
  22578. Move to the next element at the same level, when possible."
  22579. (interactive)
  22580. (cond ((eobp) (user-error "Cannot move further down"))
  22581. ((org-with-limited-levels (org-at-heading-p))
  22582. (let ((origin (point)))
  22583. (goto-char (org-end-of-subtree nil t))
  22584. (unless (org-with-limited-levels (org-at-heading-p))
  22585. (goto-char origin)
  22586. (user-error "Cannot move further down"))))
  22587. (t
  22588. (let* ((elem (org-element-at-point))
  22589. (end (org-element-property :end elem))
  22590. (parent (org-element-property :parent elem)))
  22591. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22592. (goto-char (org-element-property :end parent)))
  22593. ((integer-or-marker-p end) (goto-char end))
  22594. (t (message "No element at point")))))))
  22595. (defun org-backward-element ()
  22596. "Move backward by one element.
  22597. Move to the previous element at the same level, when possible."
  22598. (interactive)
  22599. (cond ((bobp) (user-error "Cannot move further up"))
  22600. ((org-with-limited-levels (org-at-heading-p))
  22601. ;; At a headline, move to the previous one, if any, or stay
  22602. ;; here.
  22603. (let ((origin (point)))
  22604. (org-with-limited-levels (org-backward-heading-same-level 1))
  22605. ;; When current headline has no sibling above, move to its
  22606. ;; parent.
  22607. (when (= (point) origin)
  22608. (or (org-with-limited-levels (org-up-heading-safe))
  22609. (progn (goto-char origin)
  22610. (user-error "Cannot move further up"))))))
  22611. (t
  22612. (let* ((elem (org-element-at-point))
  22613. (beg (org-element-property :begin elem)))
  22614. (cond
  22615. ;; Move to beginning of current element if point isn't
  22616. ;; there already.
  22617. ((null beg) (message "No element at point"))
  22618. ((/= (point) beg) (goto-char beg))
  22619. (t (goto-char beg)
  22620. (skip-chars-backward " \r\t\n")
  22621. (unless (bobp)
  22622. (let ((prev (org-element-at-point)))
  22623. (goto-char (org-element-property :begin prev))
  22624. (while (and (setq prev (org-element-property :parent prev))
  22625. (<= (org-element-property :end prev) beg))
  22626. (goto-char (org-element-property :begin prev)))))))))))
  22627. (defun org-up-element ()
  22628. "Move to upper element."
  22629. (interactive)
  22630. (if (org-with-limited-levels (org-at-heading-p))
  22631. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22632. (let* ((elem (org-element-at-point))
  22633. (parent (org-element-property :parent elem)))
  22634. (if parent (goto-char (org-element-property :begin parent))
  22635. (if (org-with-limited-levels (org-before-first-heading-p))
  22636. (user-error "No surrounding element")
  22637. (org-with-limited-levels (org-back-to-heading)))))))
  22638. (defvar org-element-greater-elements)
  22639. (defun org-down-element ()
  22640. "Move to inner element."
  22641. (interactive)
  22642. (let ((element (org-element-at-point)))
  22643. (cond
  22644. ((memq (org-element-type element) '(plain-list table))
  22645. (goto-char (org-element-property :contents-begin element))
  22646. (forward-char))
  22647. ((memq (org-element-type element) org-element-greater-elements)
  22648. ;; If contents are hidden, first disclose them.
  22649. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22650. (goto-char (or (org-element-property :contents-begin element)
  22651. (user-error "No content for this element"))))
  22652. (t (user-error "No inner element")))))
  22653. (defun org-drag-element-backward ()
  22654. "Move backward element at point."
  22655. (interactive)
  22656. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22657. (let* ((elem (org-element-at-point))
  22658. (prev-elem
  22659. (save-excursion
  22660. (goto-char (org-element-property :begin elem))
  22661. (skip-chars-backward " \r\t\n")
  22662. (unless (bobp)
  22663. (let* ((beg (org-element-property :begin elem))
  22664. (prev (org-element-at-point))
  22665. (up prev))
  22666. (while (and (setq up (org-element-property :parent up))
  22667. (<= (org-element-property :end up) beg))
  22668. (setq prev up))
  22669. prev)))))
  22670. ;; Error out if no previous element or previous element is
  22671. ;; a parent of the current one.
  22672. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22673. (user-error "Cannot drag element backward")
  22674. (let ((pos (point)))
  22675. (org-element-swap-A-B prev-elem elem)
  22676. (goto-char (+ (org-element-property :begin prev-elem)
  22677. (- pos (org-element-property :begin elem)))))))))
  22678. (defun org-drag-element-forward ()
  22679. "Move forward element at point."
  22680. (interactive)
  22681. (let* ((pos (point))
  22682. (elem (org-element-at-point)))
  22683. (when (= (point-max) (org-element-property :end elem))
  22684. (user-error "Cannot drag element forward"))
  22685. (goto-char (org-element-property :end elem))
  22686. (let ((next-elem (org-element-at-point)))
  22687. (when (or (org-element-nested-p elem next-elem)
  22688. (and (eq (org-element-type next-elem) 'headline)
  22689. (not (eq (org-element-type elem) 'headline))))
  22690. (goto-char pos)
  22691. (user-error "Cannot drag element forward"))
  22692. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22693. ;; body's length (without final blanks) and by the length of
  22694. ;; blanks between ELEM and NEXT-ELEM.
  22695. (let ((size-next (- (save-excursion
  22696. (goto-char (org-element-property :end next-elem))
  22697. (skip-chars-backward " \r\t\n")
  22698. (forward-line)
  22699. ;; Small correction if buffer doesn't end
  22700. ;; with a newline character.
  22701. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22702. (org-element-property :begin next-elem)))
  22703. (size-blank (- (org-element-property :end elem)
  22704. (save-excursion
  22705. (goto-char (org-element-property :end elem))
  22706. (skip-chars-backward " \r\t\n")
  22707. (forward-line)
  22708. (point)))))
  22709. (org-element-swap-A-B elem next-elem)
  22710. (goto-char (+ pos size-next size-blank))))))
  22711. (defun org-drag-line-forward (arg)
  22712. "Drag the line at point ARG lines forward."
  22713. (interactive "p")
  22714. (dotimes (_ (abs arg))
  22715. (let ((c (current-column)))
  22716. (if (< 0 arg)
  22717. (progn
  22718. (beginning-of-line 2)
  22719. (transpose-lines 1)
  22720. (beginning-of-line 0))
  22721. (transpose-lines 1)
  22722. (beginning-of-line -1))
  22723. (org-move-to-column c))))
  22724. (defun org-drag-line-backward (arg)
  22725. "Drag the line at point ARG lines backward."
  22726. (interactive "p")
  22727. (org-drag-line-forward (- arg)))
  22728. (defun org-mark-element ()
  22729. "Put point at beginning of this element, mark at end.
  22730. Interactively, if this command is repeated or (in Transient Mark
  22731. mode) if the mark is active, it marks the next element after the
  22732. ones already marked."
  22733. (interactive)
  22734. (let (deactivate-mark)
  22735. (if (and (org-called-interactively-p 'any)
  22736. (or (and (eq last-command this-command) (mark t))
  22737. (and transient-mark-mode mark-active)))
  22738. (set-mark
  22739. (save-excursion
  22740. (goto-char (mark))
  22741. (goto-char (org-element-property :end (org-element-at-point)))))
  22742. (let ((element (org-element-at-point)))
  22743. (end-of-line)
  22744. (push-mark (org-element-property :end element) t t)
  22745. (goto-char (org-element-property :begin element))))))
  22746. (defun org-narrow-to-element ()
  22747. "Narrow buffer to current element."
  22748. (interactive)
  22749. (let ((elem (org-element-at-point)))
  22750. (cond
  22751. ((eq (car elem) 'headline)
  22752. (narrow-to-region
  22753. (org-element-property :begin elem)
  22754. (org-element-property :end elem)))
  22755. ((memq (car elem) org-element-greater-elements)
  22756. (narrow-to-region
  22757. (org-element-property :contents-begin elem)
  22758. (org-element-property :contents-end elem)))
  22759. (t
  22760. (narrow-to-region
  22761. (org-element-property :begin elem)
  22762. (org-element-property :end elem))))))
  22763. (defun org-transpose-element ()
  22764. "Transpose current and previous elements, keeping blank lines between.
  22765. Point is moved after both elements."
  22766. (interactive)
  22767. (org-skip-whitespace)
  22768. (let ((end (org-element-property :end (org-element-at-point))))
  22769. (org-drag-element-backward)
  22770. (goto-char end)))
  22771. (defun org-unindent-buffer ()
  22772. "Un-indent the visible part of the buffer.
  22773. Relative indentation (between items, inside blocks, etc.) isn't
  22774. modified."
  22775. (interactive)
  22776. (unless (eq major-mode 'org-mode)
  22777. (user-error "Cannot un-indent a buffer not in Org mode"))
  22778. (let* ((parse-tree (org-element-parse-buffer 'greater-element))
  22779. unindent-tree ; For byte-compiler.
  22780. (unindent-tree
  22781. (function
  22782. (lambda (contents)
  22783. (mapc
  22784. (lambda (element)
  22785. (if (memq (org-element-type element) '(headline section))
  22786. (funcall unindent-tree (org-element-contents element))
  22787. (save-excursion
  22788. (save-restriction
  22789. (narrow-to-region
  22790. (org-element-property :begin element)
  22791. (org-element-property :end element))
  22792. (org-do-remove-indentation)))))
  22793. (reverse contents))))))
  22794. (funcall unindent-tree (org-element-contents parse-tree))))
  22795. (defun org-show-children (&optional level)
  22796. "Show all direct subheadings of this heading.
  22797. Prefix arg LEVEL is how many levels below the current level
  22798. should be shown. Default is enough to cause the following
  22799. heading to appear."
  22800. (interactive "p")
  22801. ;; If `orgstruct-mode' is active, use the slower version.
  22802. (if orgstruct-mode (call-interactively #'outline-show-children)
  22803. (save-excursion
  22804. (org-back-to-heading t)
  22805. (let* ((current-level (funcall outline-level))
  22806. (max-level (org-get-valid-level
  22807. current-level
  22808. (if level (prefix-numeric-value level) 1)))
  22809. (end (save-excursion (org-end-of-subtree t t)))
  22810. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22811. (past-first-child nil)
  22812. ;; Make sure to skip inlinetasks.
  22813. (re (format regexp-fmt
  22814. current-level
  22815. (cond
  22816. ((not (featurep 'org-inlinetask)) "")
  22817. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22818. 3))
  22819. (t (1- org-inlinetask-min-level))))))
  22820. ;; Display parent heading.
  22821. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22822. (forward-line)
  22823. ;; Display children. First child may be deeper than expected
  22824. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22825. ;; MAX-LEVEL accordingly.
  22826. (while (re-search-forward re end t)
  22827. (unless past-first-child
  22828. (setq re (format regexp-fmt
  22829. current-level
  22830. (max (funcall outline-level) max-level)))
  22831. (setq past-first-child t))
  22832. (outline-flag-region
  22833. (line-end-position 0) (line-end-position) nil))))))
  22834. (defun org-show-subtree ()
  22835. "Show everything after this heading at deeper levels."
  22836. (interactive)
  22837. (outline-flag-region
  22838. (point)
  22839. (save-excursion
  22840. (org-end-of-subtree t t))
  22841. nil))
  22842. (defun org-show-entry ()
  22843. "Show the body directly following this heading.
  22844. Show the heading too, if it is currently invisible."
  22845. (interactive)
  22846. (save-excursion
  22847. (ignore-errors
  22848. (org-back-to-heading t)
  22849. (outline-flag-region
  22850. (max (point-min) (1- (point)))
  22851. (save-excursion
  22852. (if (re-search-forward
  22853. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22854. (match-beginning 1)
  22855. (point-max)))
  22856. nil)
  22857. (org-cycle-hide-drawers 'children))))
  22858. (defun org-make-options-regexp (kwds &optional extra)
  22859. "Make a regular expression for keyword lines.
  22860. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22861. when non-nil, is a regexp matching keywords names."
  22862. (concat "^[ \t]*#\\+\\("
  22863. (regexp-opt kwds)
  22864. (and extra (concat (and kwds "\\|") extra))
  22865. "\\):[ \t]*\\(.*\\)"))
  22866. ;; Make isearch reveal the necessary context
  22867. (defun org-isearch-end ()
  22868. "Reveal context after isearch exits."
  22869. (when isearch-success ; only if search was successful
  22870. (if (featurep 'xemacs)
  22871. ;; Under XEmacs, the hook is run in the correct place,
  22872. ;; we directly show the context.
  22873. (org-show-context 'isearch)
  22874. ;; In Emacs the hook runs *before* restoring the overlays.
  22875. ;; So we have to use a one-time post-command-hook to do this.
  22876. ;; (Emacs 22 has a special variable, see function `org-mode')
  22877. (unless (and (boundp 'isearch-mode-end-hook-quit)
  22878. isearch-mode-end-hook-quit)
  22879. ;; Only when the isearch was not quitted.
  22880. (org-add-hook 'post-command-hook 'org-isearch-post-command
  22881. 'append 'local)))))
  22882. (defun org-isearch-post-command ()
  22883. "Remove self from hook, and show context."
  22884. (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
  22885. (org-show-context 'isearch))
  22886. ;;;; Integration with and fixes for other packages
  22887. ;;; Imenu support
  22888. (defvar-local org-imenu-markers nil
  22889. "All markers currently used by Imenu.")
  22890. (defun org-imenu-new-marker (&optional pos)
  22891. "Return a new marker for use by Imenu, and remember the marker."
  22892. (let ((m (make-marker)))
  22893. (move-marker m (or pos (point)))
  22894. (push m org-imenu-markers)
  22895. m))
  22896. (defun org-imenu-get-tree ()
  22897. "Produce the index for Imenu."
  22898. (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
  22899. (setq org-imenu-markers nil)
  22900. (let* ((n org-imenu-depth)
  22901. (re (concat "^" (org-get-limited-outline-regexp)))
  22902. (subs (make-vector (1+ n) nil))
  22903. (last-level 0)
  22904. m level head0 head)
  22905. (save-excursion
  22906. (save-restriction
  22907. (widen)
  22908. (goto-char (point-max))
  22909. (while (re-search-backward re nil t)
  22910. (setq level (org-reduced-level (funcall outline-level)))
  22911. (when (and (<= level n)
  22912. (looking-at org-complex-heading-regexp)
  22913. (setq head0 (org-match-string-no-properties 4)))
  22914. (setq head (org-link-display-format head0)
  22915. m (org-imenu-new-marker))
  22916. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22917. (if (>= level last-level)
  22918. (push (cons head m) (aref subs level))
  22919. (push (cons head (aref subs (1+ level))) (aref subs level))
  22920. (loop for i from (1+ level) to n do (aset subs i nil)))
  22921. (setq last-level level)))))
  22922. (aref subs 1)))
  22923. (eval-after-load "imenu"
  22924. '(progn
  22925. (add-hook 'imenu-after-jump-hook
  22926. (lambda ()
  22927. (when (derived-mode-p 'org-mode)
  22928. (org-show-context 'org-goto))))))
  22929. (defun org-link-display-format (link)
  22930. "Replace a link with its the description.
  22931. If there is no description, use the link target."
  22932. (save-match-data
  22933. (if (string-match org-bracket-link-analytic-regexp link)
  22934. (replace-match (if (match-end 5)
  22935. (match-string 5 link)
  22936. (concat (match-string 1 link)
  22937. (match-string 3 link)))
  22938. nil t link)
  22939. link)))
  22940. (defun org-toggle-link-display ()
  22941. "Toggle the literal or descriptive display of links."
  22942. (interactive)
  22943. (if org-descriptive-links
  22944. (progn (org-remove-from-invisibility-spec '(org-link))
  22945. (org-restart-font-lock)
  22946. (setq org-descriptive-links nil))
  22947. (progn (add-to-invisibility-spec '(org-link))
  22948. (org-restart-font-lock)
  22949. (setq org-descriptive-links t))))
  22950. ;; Speedbar support
  22951. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22952. "Overlay marking the agenda restriction line in speedbar.")
  22953. (overlay-put org-speedbar-restriction-lock-overlay
  22954. 'face 'org-agenda-restriction-lock)
  22955. (overlay-put org-speedbar-restriction-lock-overlay
  22956. 'help-echo "Agendas are currently limited to this item.")
  22957. (org-detach-overlay org-speedbar-restriction-lock-overlay)
  22958. (defun org-speedbar-set-agenda-restriction ()
  22959. "Restrict future agenda commands to the location at point in speedbar.
  22960. To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
  22961. (interactive)
  22962. (require 'org-agenda)
  22963. (let (p m tp np dir txt)
  22964. (cond
  22965. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22966. 'org-imenu t))
  22967. (setq m (get-text-property p 'org-imenu-marker))
  22968. (with-current-buffer (marker-buffer m)
  22969. (goto-char m)
  22970. (org-agenda-set-restriction-lock 'subtree)))
  22971. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22972. 'speedbar-function 'speedbar-find-file))
  22973. (setq tp (previous-single-property-change
  22974. (1+ p) 'speedbar-function)
  22975. np (next-single-property-change
  22976. tp 'speedbar-function)
  22977. dir (speedbar-line-directory)
  22978. txt (buffer-substring-no-properties (or tp (point-min))
  22979. (or np (point-max))))
  22980. (with-current-buffer (find-file-noselect
  22981. (let ((default-directory dir))
  22982. (expand-file-name txt)))
  22983. (unless (derived-mode-p 'org-mode)
  22984. (user-error "Cannot restrict to non-Org-mode file"))
  22985. (org-agenda-set-restriction-lock 'file)))
  22986. (t (user-error "Don't know how to restrict Org-mode's agenda")))
  22987. (move-overlay org-speedbar-restriction-lock-overlay
  22988. (point-at-bol) (point-at-eol))
  22989. (setq current-prefix-arg nil)
  22990. (org-agenda-maybe-redo)))
  22991. (defvar speedbar-file-key-map)
  22992. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22993. (eval-after-load "speedbar"
  22994. '(progn
  22995. (speedbar-add-supported-extension ".org")
  22996. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22997. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22998. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22999. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  23000. (add-hook 'speedbar-visiting-tag-hook
  23001. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  23002. ;;; Fixes and Hacks for problems with other packages
  23003. (defun org--flyspell-object-check-p (element)
  23004. "Non-nil when Flyspell can check object at point.
  23005. ELEMENT is the element at point."
  23006. (let ((object (save-excursion
  23007. (when (org-looking-at-p "\\>") (backward-char))
  23008. (org-element-context element))))
  23009. (case (org-element-type object)
  23010. ;; Prevent checks in links due to keybinding conflict with
  23011. ;; Flyspell.
  23012. ((code entity export-snippet inline-babel-call
  23013. inline-src-block line-break latex-fragment link macro
  23014. statistics-cookie target timestamp verbatim)
  23015. nil)
  23016. (footnote-reference
  23017. ;; Only in inline footnotes, within the definition.
  23018. (and (eq (org-element-property :type object) 'inline)
  23019. (< (save-excursion
  23020. (goto-char (org-element-property :begin object))
  23021. (search-forward ":" nil t 2))
  23022. (point))))
  23023. (otherwise t))))
  23024. (defun org-mode-flyspell-verify ()
  23025. "Function used for `flyspell-generic-check-word-predicate'."
  23026. (if (org-at-heading-p)
  23027. ;; At a headline or an inlinetask, check title only. This is
  23028. ;; faster than relying on `org-element-at-point'.
  23029. (and (save-excursion (beginning-of-line)
  23030. (and (let ((case-fold-search t))
  23031. (not (looking-at "\\*+ END[ \t]*$")))
  23032. (looking-at org-complex-heading-regexp)))
  23033. (match-beginning 4)
  23034. (>= (point) (match-beginning 4))
  23035. (or (not (match-beginning 5))
  23036. (< (point) (match-beginning 5))))
  23037. (let* ((element (org-element-at-point))
  23038. (post-affiliated (org-element-property :post-affiliated element)))
  23039. (cond
  23040. ;; Ignore checks in all affiliated keywords but captions.
  23041. ((< (point) post-affiliated)
  23042. (and (save-excursion
  23043. (beginning-of-line)
  23044. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  23045. (> (point) (match-end 0))
  23046. (org--flyspell-object-check-p element)))
  23047. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  23048. ((let ((log (org-log-into-drawer)))
  23049. (and log
  23050. (let ((drawer (org-element-lineage element '(drawer))))
  23051. (and drawer
  23052. (eq (compare-strings
  23053. log nil nil
  23054. (org-element-property :drawer-name drawer) nil nil t)
  23055. t)))))
  23056. nil)
  23057. (t
  23058. (case (org-element-type element)
  23059. ((comment quote-section) t)
  23060. (comment-block
  23061. ;; Allow checks between block markers, not on them.
  23062. (and (> (line-beginning-position) post-affiliated)
  23063. (save-excursion
  23064. (end-of-line)
  23065. (skip-chars-forward " \r\t\n")
  23066. (< (point) (org-element-property :end element)))))
  23067. ;; Arbitrary list of keywords where checks are meaningful.
  23068. ;; Make sure point is on the value part of the element.
  23069. (keyword
  23070. (and (member (org-element-property :key element)
  23071. '("DESCRIPTION" "TITLE"))
  23072. (save-excursion
  23073. (search-backward ":" (line-beginning-position) t))))
  23074. ;; Check is globally allowed in paragraphs verse blocks and
  23075. ;; table rows (after affiliated keywords) but some objects
  23076. ;; must not be affected.
  23077. ((paragraph table-row verse-block)
  23078. (let ((cbeg (org-element-property :contents-begin element))
  23079. (cend (org-element-property :contents-end element)))
  23080. (and cbeg (>= (point) cbeg) (< (point) cend)
  23081. (org--flyspell-object-check-p element))))))))))
  23082. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  23083. (defun org-remove-flyspell-overlays-in (beg end)
  23084. "Remove flyspell overlays in region."
  23085. (and (org-bound-and-true-p flyspell-mode)
  23086. (fboundp 'flyspell-delete-region-overlays)
  23087. (flyspell-delete-region-overlays beg end)))
  23088. (defvar flyspell-delayed-commands)
  23089. (eval-after-load "flyspell"
  23090. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  23091. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  23092. (eval-after-load "bookmark"
  23093. '(if (boundp 'bookmark-after-jump-hook)
  23094. ;; We can use the hook
  23095. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23096. ;; Hook not available, use advice
  23097. (defadvice bookmark-jump (after org-make-visible activate)
  23098. "Make the position visible."
  23099. (org-bookmark-jump-unhide))))
  23100. ;; Make sure saveplace shows the location if it was hidden
  23101. (eval-after-load "saveplace"
  23102. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23103. "Make the position visible."
  23104. (org-bookmark-jump-unhide)))
  23105. ;; Make sure ecb shows the location if it was hidden
  23106. (eval-after-load "ecb"
  23107. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23108. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23109. (when (derived-mode-p 'org-mode)
  23110. (org-show-context))))
  23111. (defun org-bookmark-jump-unhide ()
  23112. "Unhide the current position, to show the bookmark location."
  23113. (and (derived-mode-p 'org-mode)
  23114. (or (outline-invisible-p)
  23115. (save-excursion (goto-char (max (point-min) (1- (point))))
  23116. (outline-invisible-p)))
  23117. (org-show-context 'bookmark-jump)))
  23118. (defun org-mark-jump-unhide ()
  23119. "Make the point visible with `org-show-context' after jumping to the mark."
  23120. (when (and (derived-mode-p 'org-mode)
  23121. (outline-invisible-p))
  23122. (org-show-context 'mark-goto)))
  23123. (eval-after-load "simple"
  23124. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23125. "Make the point visible with `org-show-context'."
  23126. (org-mark-jump-unhide)))
  23127. (eval-after-load "simple"
  23128. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23129. "Make the point visible with `org-show-context'."
  23130. (org-mark-jump-unhide)))
  23131. (eval-after-load "simple"
  23132. '(defadvice pop-global-mark (after org-make-visible activate)
  23133. "Make the point visible with `org-show-context'."
  23134. (org-mark-jump-unhide)))
  23135. ;; Make session.el ignore our circular variable
  23136. (defvar session-globals-exclude)
  23137. (eval-after-load "session"
  23138. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23139. ;;;; Finish up
  23140. (provide 'org)
  23141. (run-hooks 'org-load-hook)
  23142. ;;; org.el ends here