Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Tree: cf9c987988
Fetching contributors…

Cannot retrieve contributors at this time

8424 lines (7908 sloc) 306.044 kB
" org.vim - VimOrganizer plugin for Vim
" -------------------------------------------------------------
" Version: 0.30
" Maintainer: Herbert Sitz <hesitz@gmail.com>
" Last Change: 2011 Nov 02
"
" Script: http://www.vim.org/scripts/script.php?script_id=3342
" Github page: http://github.com/hsitz/VimOrganizer
" Copyright: (c) 2010, 2011 by Herbert Sitz
" The VIM LICENSE applies to all files in the
" VimOrganizer plugin.
" (See the Vim copyright except read "VimOrganizer"
" in places where that copyright refers to "Vim".)
" http://vimdoc.sourceforge.net/htmldoc/uganda.html#license
" No warranty, express or implied.
" *** *** Use At-Your-Own-Risk *** ***
"
"Section Setup
"if !exists('g:v')
" let g:v={}
"endif
" Calendar plugin at:
"http://www.vim.org/scripts/script.php?script_id=52
let b:v={}
set foldmethod=manual
let w:v={}
let b:v.prevlev = 0
let b:v.org_loaded=0
let b:v.lasttext_lev=''
let maplocalleader = "," " Org key mappings prepend single comma
let b:v.dateMatch = '\(\d\d\d\d-\d\d-\d\d\)'
let b:v.headMatch = '^\*\+\s'
let b:v.tableMatch = '^\(\s*|.*|\s*$\|#+TBLFM\)'
let b:v.taglineMatch = '^\s*:\S\+:\s*$'
let b:v.headMatchLevel = '^\(\*\)\{level}\s'
let b:v.propMatch = '^\s*:\s*\(PROPERTIES\)'
let b:v.propvalMatch = '^\s*:\s*\(\S*\)\s*:\s*\(\S.*\)\s*$'
let b:v.drawerMatch = '^\s*:\(PROPERTIES\|LOGBOOK\)'
let b:v.levelstars = 1
let b:v.effort=['0:05','0:10','0:15','0:30','0:45','1:00','1:30','2:00','4:00']
let b:v.tagMatch = '\(:\S*:\)\s*$'
let b:v.mytags = ['buy','home','work','URGENT']
let b:v.foldhi = ''
let b:v.org_inherited_properties = ['COLUMNS']
let b:v.org_inherited_defaults = {'CATEGORY':expand('%:t:r'),'COLUMNS':'%40ITEM %30TAGS'}
let b:v.heading_marks = []
let b:v.heading_marks_dict = {}
let w:v.total_columns_width = 30
let w:v.columnview = 0
let w:v.org_item_len = 100
let w:v.org_colview_list = []
let w:v.org_current_columns = ''
let w:v.org_column_item_head = ''
let b:v.chosen_agenda_heading = 0
let b:v.prop_all_dict = {}
let b:v.buf_tags_static_spec = ''
let b:v.buffer_category = ''
if !exists('g:org_agenda_default_search_spec')
let g:org_agenda_default_search_spec = 'ANY_TODO'
endif
if exists('g:global_column_defaults')
let b:v.buffer_columns = g:global_column_defaults
else
let b:v.buffer_columns = '%40ITEM %30TAGS'
endif
let w:sparse_on = 0
"if exists('g:global_column_view') && g:global_column_view==1
" let w:v.columnview = 1
"else
" let w:v.columnview = 0
"endif
let b:v.last_dict_time = 0
let b:v.last_idict_time = 0
let b:v.last_idict_type = 0
let b:v.clock_to_logbook = 1
let b:v.messages = []
let b:v.global_cycle_levels_to_show=4
let b:v.src_fold=0
let b:v.foldhilines = []
let b:v.cycle_with_text=1
let b:v.foldcolors=['Normal','SparseSkip','Folded','WarningMsg','WildMenu','DiffAdd','DiffChange','Normal','Normal','Normal','Normal']
let b:v.cols = []
setlocal cfu=Mycfu
set noswapfile
hi MatchGroup guibg=yellow guifg=black
setlocal ignorecase " searches ignore case
setlocal smartcase " searches use smart case
setlocal autoindent
setlocal fileformat=unix
setlocal backspace=2
setlocal nowrap
setlocal tw=78
setlocal expandtab
setlocal nosmarttab
setlocal softtabstop=0
setlocal foldcolumn=1
setlocal tabstop=4
setlocal shiftwidth=4
setlocal formatlistpat=^\\s*\\d\\+\\.\\s\\+\\\|^\\s*\\-\\s\\+
if has("conceal")
set conceallevel=3
set concealcursor=nc
endif
setlocal indentexpr=
setlocal foldexpr=OrgFoldLevel(v:lnum)
"setlocal iskeyword+=<
setlocal nocindent
setlocal iskeyword=@,39,45,48-57,_,129-255
let b:v.basedate = strftime("%Y-%m-%d %a")
let b:v.sparse_list = []
let b:v.fold_list = []
let b:v.suppress_indent=0
let b:v.suppress_list_indent=0
" LINE BELOW IS MAJOR IF THAT ENCOMPASSES MOST OF org.vim
" endif is near bottom of document
" everything in between is executed only the first time an
" org file is opened
if !exists('g:org_loaded')
function! s:SID()
return matchstr(expand('<sfile>'), '<SNR>\zs\d\+\ze_SID$')
endfun
let g:org_sid = s:SID()
let sid='<SNR>' . g:org_sid . '_'
function! OrgSID(func)
execute 'call <SNR>'.s:SID().'_'.a:func
endfunction
if !exists('g:org_custom_column_options')
let g:org_custom_column_options = ['%ITEM %15DEADLINE %35TAGS', '%ITEM %35TAGS']
endif
if !exists('g:org_command_for_emacsclient') && (has('unix') || has('macunix'))
let g:org_command_for_emacsclient = 'emacsclient'
endif
if !exists('g:org_custom_colors')
let g:org_custom_colors=[]
endif
if !exists('g:org_tags_persistent_alist')
let g:org_tags_persistent_alist = ''
endif
if !exists('g:org_save_when_searched')
let g:org_save_when_searched = 0
endif
if !exists('g:org_capture_file')
let g:org_capture_file = ''
endif
if !exists('g:org_sort_with_todo_words')
let g:org_sort_with_todo_words=1
endif
if !exists('g:org_tags_alist')
let g:org_tags_alist = ''
endif
if !exists('g:org_agenda_include_clocktable')
let g:org_agenda_include_clocktable = 0
endif
if !exists('g:org_confirm_babel_evaluate')
let g:org_confirm_babel_evaluate = 0
endif
if !exists('g:org_agenda_window_position')
let g:org_agenda_window_position = 'bottom'
endif
if has('win32') || has('win64')
let s:cmd_line_quote_fix = '^'
else
let s:cmd_line_quote_fix = ''
endif
let g:org_filename_wildcards = ['*.org']
let s:sfile = expand("<sfile>:p:h")
let s:last_refile_point = []
let g:org_todos_done_dict = {}
let g:org_todos_notdone_dict = {}
let g:org_agenda_todos_done_pattern = ''
let g:org_agenda_todos_notdone_pattern = ''
let g:org_clock_history=[]
let g:org_reverse_note_order = 0
let g:org_html_app=''
let g:org_pdf_app=''
let s:org_headMatch = '^\*\+\s'
let s:org_cal_date = '2000-01-01'
let g:org_export_babel_evaluate = 1
let g:org_tag_group_arrange = 0
let g:org_first_sparse=1
let g:org_clocks_in_agenda = 0
let s:remstring = '^\s*:\S'
let s:block_line = '^\s*\(:\|DEADLINE\|SCHEDULED\|CLOSED\|<\d\d\d\d-\|[\d\d\d\d-\)'
"let s:remstring = '^\s*\(:\|DEADLINE:\|SCHEDULED:\|CLOSED:\|<\d\d\d\d-\)'
let g:org_use_calendar = 1
let g:org_todoitems=[]
let s:headline = ''
let g:org_ColumnHead = 'Lines'
let g:org_gray_agenda = 0
let g:org_sparse_lines_after = 10
let g:org_log_todos=0
let g:org_timegrid=[8,20,2]
let w:v.org_colview_list = []
let s:firsttext = ''
let g:org_supported_link_types = '\(http\|file\|mailto\)'
let g:org_unsupported_link_types = '\(vm\|wl\|mhe\|rmail\|gnus\|bbdb\|irc\|info\|shell\|elisp\)'
let w:v.org_item_len=100
let w:sparse_on = 0
let g:org_folds = 1
let g:org_show_fold_lines = 1
let g:org_columns_default_width = 15
let s:org_columns_master_heading = 0
let w:v.org_colview_list=[]
let g:org_show_fold_dots = 0
let g:org_show_matches_folded=1
let g:org_indent_from_head = 0
let g:org_agenda_skip_gap = 2
let g:org_agenda_days=7
let g:org_agenda_minforskip = 8
let g:org_show_balloon_tips=1
let g:org_datelist = []
let g:org_search_spec = ''
let g:org_deadline_warning_days = 3
let s:org_weekdays = ['mon','tue','wed','thu','fri','sat','sun']
let s:org_weekdaystring = '\cmon\|tue\|wed\|thu\|fri\|sat\|sun'
let s:org_months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
let s:org_monthstring = '\c\(jan\|feb\|mar\|apr\|may\|jun\|jul\|aug\|sep\|oct\|nov\|dec\)\S*'
let s:include_inherited_props=0
let s:AgendaBufferName = "__Agenda__"
let s:sparse_lines = {}
let s:search_list = []
let s:last_search_list = []
"testing stuff
function! CustomSearchesSetup()
let g:org_custom_searches = [
\ { 'name':"Next week's agenda", 'type':'agenda',
\ 'agenda_date':'+1w','agenda_duration':'w'}
\ ,{ 'name':"Next week's TODOS", 'type':'agenda',
\ 'agenda_date':'+1w','agenda_duration':'w','spec':'+UNFINISHED_TODOS'}
\ , { 'name':'Home tags', 'type':'tags', 'spec':'+HOME'}
\ , { 'name':'Home tags', 'type':'sparse_tree', 'spec':'+HOME'}
\ , [ { 'name':"Next week's agenda", 'type':'agenda',
\ 'agenda_date':'+1w','agenda_duration':'w'}
\ ,{ 'name':'Home tags', 'type':'tags', 'spec':'+HOME'}
\ ]
\ , [ { 'name':'Home tags', 'type':'tags', 'spec':'+HOME'}
\ ,{ 'name':"Next week's agenda", 'type':'agenda',
\ 'agenda_date':'+1w','agenda_duration':'w'}
\ ]
\ ]
endfunction
function! s:RunCustom(search)
" search arg is either number of predefined custom search,
" or full spec for search from agenda dashboard
if type(a:search) == type(1)
let search_spec = g:org_custom_searches[a:search]
else
let search_spec = a:search
endif
if !exists("g:agenda_files") || (g:agenda_files == [])
if has('dialog_con') || has('dialog_gui')
unsilent call confirm("No agenda files defined. Will add current file to agenda files.")
endif
call s:CurfileAgenda()
endif
if type(search_spec) == type({})
"single spec
let s:search_list = [ search_spec ]
else
" block agenda specs
let s:search_list = search_spec
endif
let this_time_list = s:search_list
if this_time_list[0].type !~ 'sparse_tree'
let curfile = expand("%:p")
let curtab = tabpagenr()
let curwin = winnr()
:AAgenda
" delete redo block (always just one) if any
if get(this_time_list[0],'redo_num') > 0
"redo_num is block in agenda to redo
let redo_num = s:AgendaBlockNum(this_time_list[0].redo_num)
normal gg
if redo_num > 1
for i in range(1,redo_num - 1)
call search('^==============','','')
endfor
endif
let start_line = (line('.') == 1) ? 1 : line('.') + 1
let test_end = search('^=========','W','')
let end_line = test_end > 0 ? test_end - 1 : line('$')
silent exec start_line . ',' . end_line . 'delete'
call append(start_line - 1,['','']) " append to agenda buf
let s:agenda_insert_point = start_line
elseif len(this_time_list) == 1
silent exec '%d'
let s:agenda_insert_point = 1
else
let s:agenda_insert_point = line('$')
endif
endif
let i = 0
for item in this_time_list
if i > 0
call append(line('$'),['',repeat('=',70),'','']) " append to agenda buf
let s:agenda_insert_point = line('$')
endif
let mydict = item
if mydict.type ==? 'agenda'
let mydate = DateCueResult( get(mydict,'agenda_date',''), s:Today())
let mydur = get(mydict, 'agenda_duration','w')
let mydur = (mydur == 'w') ? '7' : (mydur == 'd' ? '1' : mydur)
call OrgRunAgenda( mydate,
\ get(mydict, 'agenda_duration', 'w'),
\ get(mydict, 'spec','') )
let save_line = line('.')
let last_line = search('^============','W','') - 1
exec (last_line <= 0) ? line('$') : last_line
if (g:org_agenda_include_clocktable == 1)
call append(line('.'),OrgGetClocktable(g:agenda_files,' :narrow 40! :tstart ' . '"<' . mydate . ' xxx 00:00>" :tend "<' . calutil#cal(calutil#jul(mydate) + mydur ) . ' xxx 00:00>" :link ')[3:-3])
endif
exec save_line
elseif mydict.type ==? 'sparse_tree'
call OrgRunSearch( mydict.spec, 1 )
elseif mydict.type ==? 'sparse_tree_regex'
silent call s:SparseTreeRun(mydict.spec)
elseif mydict.type ==? 'tags'
call OrgRunSearch( mydict.spec )
elseif mydict.type ==? 'tags-todo'
" add todos to spec
call OrgRunSearch( mydict.spec,'agenda_todo' )
endif
let i += 1
endfor
set foldlevel=999
execute s:agenda_insert_point
nohl
endfunction
"Section Tag and Todo Funcs
function! OrgProcessConfigLines()
let b:v.org_config_lines = []
let b:v.todoitems = []
silent g/^#+/call add( b:v.org_config_lines, getline(line('.')) )
" clear out for new tag settings
let b:v.tagdict = {}
let b:v.buf_tags_static_spec = ''
let b:v.tagchars=''
let b:v.tags_order = []
if g:org_tags_alist ==# ''
let b:v.dynamic_tags=1
else
let b:v.dynamic_tags=0
endif
for line in b:v.org_config_lines
if line =~ '^#+CATEGORY'
let b:v.buffer_category = matchstr( line ,'^#+CATEGORY:\s*\zs.*')
let b:v.org_inherited_defaults['CATEGORY'] = b:v.buffer_category
elseif line =~ '^#+COLUMNS'
let b:v.buffer_columns = matchstr( line ,'^#+COLUMNS:\s*\zs.*')
let b:v.org_inherited_defaults['COLUMNS'] = b:v.buffer_columns
"let w:v.org_current_columns = b:v.buffer_columns
elseif line =~ '#+STARTUP:'
let startup_list = split(matchstr( line, '#+STARTUP:\s*\zs.*') )
for item in startup_list
silent! exec "let b:v." . item . "=1"
endfor
elseif line =~ '#+TAGS:'
let newtags = matchstr( line, '#+TAGS:\s*\zs.*')
if newtags ==# ''
let b:v.dynamic_tags = 1
else
let b:v.buf_tags_static_spec .= newtags . ' \n '
endif
elseif line =~ '\(#+TODO:\|#+SEQ_TODO:\)'
call OrgTodoSetup(matchstr(line,'\(#+TODO:\|#+SEQ_TODO:\)\s*\zs.*'))
elseif line =~ '#+PROPERTY:'
let m = matchlist(line,'.\{-}:\s*\(.\{-}\)_ALL \(.*\)')
if m[2] ># ''
let b:v.prop_all_dict[toupper(m[1])] = m[2]
endif
endif
endfor
if empty(b:v.todoitems)
call OrgTodoSetup(g:org_todo_setup)
endif
call OrgTagSetup( b:v.buf_tags_static_spec )
" get rid of b:v.buffer_category (and columns also) and just use o_i_d var???
if b:v.buffer_category ==# ''
let b:v.buffer_category = expand("%:t:r")
endif
normal gg
endfunction
function! s:EditProp(property)
let s:edit_prop = toupper(a:property)
let propval = get(s:GetProperties(line('.'),0), s:edit_prop,'')
function! s:PropCompleteFunc(arghead, sd, gf)
let prop = matchstr(a:sd,'^.\{-}\ze:')
let valuelist = split(get(b:v.prop_all_dict, s:edit_prop, ''))
let matches = filter(valuelist, 'v:val =~ a:arghead')
return join(matches, "\n")
endfunction
let myfunc = '<SNR>' . s:SID() . '_PropCompleteFunc'
let newval = input("Enter value for " . s:edit_prop . ": ", propval, 'custom,' . myfunc)
if newval != propval
call s:SetProp(s:edit_prop, newval)
echo s:edit_prop . " changed to: " newval
else
echo s:edit_prop . " not changed."
endif
endfunction
function! OrgTodoConvert(orgtodo)
let todolist = []
let sublist = []
let b:v.tododict = {}
" let templist = []
let temp_list = split(a:orgtodo,'\s\+')
for item in temp_list
if item == '|'
continue
endif
let b:v.tododict[item] = {}
if matchstr(item,'.*(.)') ==# ''
let b:v.tododict[item].todotext = item
let b:v.tododict[item].todochar = ''
else
let b:v.tododict[item].todotext = matchstr(item,'.*\ze(.)')
let b:v.tododict[item].todochar = matchstr(item,'.*(\zs.\ze)')
endif
endfor
" count '|' chars in list, if 0 or 1 then
" it is like Org-mode format, otherwise
" sublists are used in non-done slot"
let bar_count = count(split(a:orgtodo,'\zs'),'|')
let after_bar = 0
if bar_count >= 2
for item in temp_list
if item != '|'
call add(sublist,item)
elseif (item ==? '|')
call add(todolist,sublist)
let sublist = []
endif
endfor
else
for item in temp_list
if (item != '|') && (after_bar == 1)
call add(sublist,item)
elseif (item != '|') && (after_bar == 0)
call add(todolist,item)
elseif (item ==? '|')
let sublist = []
let after_bar = 1
endif
endfor
endif
if sublist != []
call add(todolist,sublist)
endif
return todolist
endfunction
function! OrgTodoSetup(todolist_str)
let todolist = OrgTodoConvert(a:todolist_str)
let b:v.todo_setup = a:todolist_str
"set up list and patterns for use throughout
let b:v.todoitems=[]
let b:v.todo_first_letters = ''
"let b:v.fulltodos=todolist
let b:v.todocycle=[]
let b:v.todoMatch=''
let b:v.todoNotDoneMatch=''
let b:v.todoDoneMatch=''
let i = 0
while i < len(todolist)
if type(todolist[i]) == type('abc')
let thistodo = matchstr(todolist[i],'.*ze(.)')
let thistodo = b:v.tododict[todolist[i]].todotext
let todolist[i] = substitute(todolist[i],'(.)','','')
call add(b:v.todoitems,thistodo)
call add(b:v.todocycle,thistodo)
" add to patterns
"let newtodo = b:v.todoitems[len(b:v.todoitems)-1]
let newtodo = thistodo
let b:v.todoMatch .= newtodo . '\|'
if i < len(todolist) - 1
let b:v.todoNotDoneMatch .= newtodo . '\|'
let g:org_todos_notdone_dict[newtodo] = 1
else
let b:v.todoDoneMatch .= newtodo . '\|'
let g:org_todos_done_dict[newtodo] = 1
endif
else
"item is itself a list
let j = 0
while j < len(todolist[i])
let thisitem = b:v.tododict[todolist[i][j]].todotext
let todolist[i][j] = substitute(todolist[i][j],'(.)','','')
call add(b:v.todoitems,thisitem )
if j == 0
call add(b:v.todocycle,thisitem)
endif
" add to patterns
let b:v.todoMatch .= thisitem . '\|'
if i < len(todolist) - 1
let b:v.todoNotDoneMatch .= thisitem . '\|'
let g:org_todos_notdone_dict[thisitem] = 1
else
let b:v.todoDoneMatch .= thisitem . '\|'
let g:org_todos_done_dict[thisitem] = 1
endif
let j += 1
endwhile
endif
let i += 1
endwhile
let b:v.todoMatch = '^\*\+\s*\zs\('.b:v.todoMatch[:-2] . ')'
let b:v.todoDoneMatch = '^\*\+\s*\zs\('.b:v.todoDoneMatch[:-2] . ')'
let b:v.todoNotDoneMatch = '^\*\+\s*\zs\('.b:v.todoNotDoneMatch[:-2] . ')'
let b:v.fulltodos = todolist
syntax clear DONETODO
exec 'syntax match DONETODO /' . b:v.todoDoneMatch . '/ containedin=OL1,OL2,OL3,OL4,OL5,OL6'
syntax clear NOTDONETODO
exec 'syntax match NOTDONETODO /' . b:v.todoNotDoneMatch . '/ containedin=OL1,OL2,OL3,OL4,OL5,OL6'
for item in keys( b:v.tododict )
let item_char = tolower( b:v.tododict[item].todochar)
if item_char ==# ''
let item_char = tolower(item[0])
endif
endfor
endfunction
function! s:CurfileAgenda()
exec "let g:agenda_files=['".expand("%:p")."']"
endfunction
function! OrgTagSetup(tagspec)
let b:v.tags = split(tr(a:tagspec,'{}',' '),'\s\+')
for item in b:v.tags
if item =~ '('
let char = matchstr(item,'(\zs.\ze)')
let tag = matchstr(item,'.*\ze(')
else
"find an unused character
let char = ''
let tag = item
let i = 0
while i < len(item)
"if !has_key(chardict, item[i])
" find char that isn't in tagchars yet
if b:v.tagchars !~ item[i]
let char = item[i]
"let chardict[item[i]] = 1
break
endif
let i += 1
endwhile
if char ==# ''
for i in range(65,90)
if b:v.tagchars !~ nr2char(i)
let char = nr2char(i)
break
endif
endfor
endif
endif
let b:v.tagdict[item] = {'char':char, 'tag':tag, 'exclude':'', 'exgroup':0}
call add(b:v.tags_order,item)
if char != ''
let b:v.tagchars .= char
endif
endfor
let templist = a:tagspec
let i = 1
while templist =~ '{.\{}}'
"cycle through groups and add exclude chars for any group members
let strikeout = matchstr(templist,'{.\{-}}')
let exclusive = matchstr(templist,'{\zs.\{-}\ze}')
let templist = substitute(templist,strikeout,'','')
let xlist = split(exclusive,'\s\+')
for item in xlist
let b:v.tagdict[item].exgroup = i
for x in xlist
if x != item
let b:v.tagdict[item].exclude .= b:v.tagdict[x].char
endif
endfor
endfor
let i += 1
endwhile
endfunction
function! OrgTagsEdit(...)
let line_file_str = ''
let lineno=line('.')
let file = expand("%")
if bufname("%") ==? ('__Agenda__')
" new file and lineno below to test with new line marker in agenda
let file = s:filedict[str2nr(matchstr(getline(line('.')), '^\d\d\d'))]
let lineno = str2nr(matchstr(getline(line('.')),'^\d\d\d\zs\d*'))
call org#SaveLocation()
call org#LocateFile(file)
call s:SetDynamicTags()
call org#RestoreLocation()
let b:v.tagdict = getbufvar(file,'v').tagdict
let b:v.tags_order = getbufvar(file,'v').tags_order
else
call s:SetDynamicTags()
endif
let heading_tags = get(s:GetProperties(lineno,0,file),'TAGS','')
let new_heading_tags = s:TagMenu(heading_tags)
if new_heading_tags != heading_tags
silent call s:SetProp('tags',new_heading_tags,lineno, file)
endif
endfunction
function! s:TagMenu(heading_tags)
let heading_tags = a:heading_tags
let tagstring = ''
let tagchars = ''
for item in b:v.tags_order
let tagchars .= b:v.tagdict[item].char
if match(heading_tags,':'.b:v.tagdict[item].tag .':') >= 0
let tagstring .= b:v.tagdict[item].char
endif
endfor
hi Cursor guibg=black
let cue = ''
set nomore
while 1
echo repeat('-',winwidth(0)-1)
echohl Title | echo 'Choose tags: ' | echohl None | echon '( <enter> to accept, <esc> to cancel )'
echo '------------'
let oldgroup = 0
let items_in_row = 1
for item in b:v.tags_order
if item ==? '\n'
continue
endif
let curindex = index(b:v.tags_order,item)
let newgroup = b:v.tagdict[item].exgroup
let select = ' '
if match(tagstring,b:v.tagdict[item].char) >= 0
let select = 'X'
echohl Question
else
echohl None
endif
"if (g:org_tag_group_arrange == 0) || (newgroup != oldgroup) || (newgroup == 0 ) || (b:v.tags_order[curindex+1] ==? '\n')
if (curindex == 0) || (b:v.tags_order[curindex-1] ==? '\n') || (winwidth(0) - (items_in_row*20) < 20)
echo repeat(' ',3) . '[' | echohl Question | echon select | echohl None | echon '] '
echohl None | echon b:v.tagdict[item].tag | echohl Title | echon '('.b:v.tagdict[item].char.')' | echohl None
let nextindent = repeat(' ',12-len(b:v.tagdict[item].tag))
let items_in_row = 1
else
"echon repeat(' ',3) .
echon nextindent
echon '[' | echohl Question | echon select | echohl None | echon '] '
echohl None | echon b:v.tagdict[item].tag | echohl Title | echon '('.b:v.tagdict[item].char.')' | echohl None
let nextindent = repeat(' ',12-len(b:v.tagdict[item].tag))
let items_in_row += 1
"echon repeat(' ', 12-len(b:v.tagdict[item]))
endif
let oldgroup = b:v.tagdict[item].exgroup
endfor
echo ""
"echohl LineNr | echon 'Date+time ['.basedate . ' '.basetime.']: '
"echohl None | echon cue.'_ =>' | echohl WildMenu | echon ' '.newdate.' '.newtime
let nchar = getchar()
let newchar = nr2char(nchar)
if (nchar ==? "\<BS>") && (len(cue)>0)
let cue = cue[:-2]
elseif nchar ==? "\<s-c-up>"
let cue = ((curdif-365>=0) ?'+':'').(curdif-365).'d'
elseif newchar ==? "\<s-cr>"
" add new tag . . . todo . . .
elseif newchar ==? "\<cr>"
break
elseif newchar ==? "\<Esc>"
hi Cursor guibg=gray
redraw
return a:heading_tags
elseif (match(tagchars,newchar) >= 0)
if (match(tagstring,newchar) == -1)
let tagstring .= newchar
" check for mutually exclusve tags
for item in keys(b:v.tagdict)
if b:v.tagdict[item].char ==? newchar
let exclude_str = b:v.tagdict[item].exclude
let tagstring = tr(tagstring,exclude_str,repeat(' ',len(exclude_str)))
break
endif
endfor
else
let tagstring = tr(tagstring,newchar,' ')
endif
endif
call substitute(tagstring,' ','','')
echon repeat(' ',72)
redraw
endwhile
hi Cursor guibg=gray
redraw
echo
set more
let heading_tags = ''
for item in keys(b:v.tagdict)
if (item!='\n') && (match(tagstring, b:v.tagdict[item].char) >= 0)
let heading_tags .= b:v.tagdict[item].tag . ':'
endif
endfor
if heading_tags ># '' | let heading_tags = ':' . heading_tags | endif
return heading_tags
endfunction
function! s:SetDynamicTags()
let taglist = s:GetBufferTags()
let chardict = {}
let b:v.tagdict = {}
let b:v.tagchars = ''
let b:v.tags_order = []
if b:v.buf_tags_static_spec ==# ''
let static_tags = g:org_tags_alist . ' ' . g:org_tags_persistent_alist
if static_tags ==# ''
let b:v.dynamic_tags_only = 1
endif
elseif exists('b:v.noptags')
let static_tags = b:v.buf_tags_static_spec
else
let static_tags = b:v.buf_tags_static_spec . ' ' . g:org_tags_persistent_alist
endif
if exists('b:v.dynamic_tags_only') && (b:v.dynamic_tags_only == 1)
let setup_string = join(taglist)
elseif exists('b:v.dynamic_tags') && (b:v.dynamic_tags == 1)
"first need to remove dups in dynamic taglist
let temp_list = split(static_tags)
for i in range(0,len(temp_list)-1)
if temp_list[i] =~ '(.)'
let temp_list[i] = matchstr(temp_list[i],'^.*\ze(')
endif
endfor
let dup_list = s:Intersect( temp_list, taglist )
for item in dup_list
call remove( taglist, index(taglist, item) )
endfor
let setup_string = static_tags . ' ' . join(taglist)
else
let setup_string = static_tags
endif
call OrgTagSetup( setup_string )
endfunction
function! s:GetBufferTags()
let save_cursor = getpos(".")
let b:v.buftagdict = {}
" call addtags for each headline in buffer
g/^\*/call s:AddTagsToDict(line("."))
call setpos('.',save_cursor)
return sort(keys(b:v.buftagdict))
endfunction
inoremap <F5> <C-R>=OrgEffort()<CR>
noremap <F5> A<C-R>=OrgEffort()<CR>
function! OrgEffort()
if getline(line('.'))=~':Effort:'
call setline(line('.'), substitute(getline(line('.')),'ort:\zs.*','',''))
normal A
call complete(col('.'),b:v.effort)
endif
return ''
endfunction
function! s:AddTagsToDict(line)
let taglist = s:GetTagList(a:line)
if !empty(taglist)
for item in taglist
execute "let b:v.buftagdict['" . item . "'] = 1"
endfor
endif
endfunction
function! s:GetTagList(line)
let text = getline(a:line+1)
if (text !~ b:v.drawerMatch) && (text !~ b:v.dateMatch) && (text =~ s:remstring)
let tags = matchlist(text,':\(\S*\):\s*$')
" include replacement of mistaken double colons with single colon
let tagstr = substitute(tags[1],'::',':','g')
if !empty(tags)
return split(tagstr,':')
else
return []
endif
else
return []
endif
endfunction
function! s:IsTagLine(line)
let text = getline(a:line)
return (text !~ b:v.drawerMatch) && (text !~ b:v.dateMatch) && (text =~ s:remstring)
endfunction
function! s:GetTags(line)
if s:IsTagLine(a:line+1)
return matchstr(getline(a:line+1),':.*$')
else
return ''
endif
endfunction
function! s:AddTag(tag,line)
if s:IsTagLine(a:line + 1)
if matchstr(getline(a:line+1),':'.a:tag.':') ==# ''
call setline(a:line+1,getline(a:line+1) . ':' .a:tag. ':')
endif
else
call append(a:line, ' :' . a:tag . ':')
endif
endfunction
function! s:TagInput(line)
let linetags = s:GetTagList(a:line)
if empty(linetags)
call append(a:line,':')
endif
let buftags = s:GetBufferTags()
let displaytags = deepcopy(buftags)
call insert(displaytags,' Exit Menu')
while 1
let curstatus = []
call add(curstatus,0)
let i = 1
let linetags = s:GetTagList(a:line)
while i < len(buftags) + 1
if index(linetags, buftags[i-1]) >= 0
let cbox = '[ X ]'
call add(curstatus,1)
else
let cbox = ' '
call add(curstatus,0)
endif
let displaytags[i] = cbox . s:PrePad('&'.buftags[i-1],28)
let i += 1
endwhile
let @/=''
if foldclosed(a:line) > 0
let b:v.sparse_list = [a:line]
else
normal V
endif
redraw
if foldclosed(a:line) > 0
let b:v.sparse_list = []
else
normal V
endif
"call insert(displaytags,'Choose tags below:')
"let key = inputlist(displaytags) - 1
let taglist = join(displaytags,"\n")
set guioptions+=v
let key = confirm('Choose tags:',taglist)-1
set guioptions-=v
"call remove(displaytags,0)
if (key == 0) " || (key == 1)
" need setline for final redraw
call setline(a:line+1,getline(a:line+1))
redraw
break
endif
let curstatus[key] = 1 - curstatus[key]
let newtags = ''
let i = 1
while i < len(curstatus)
if curstatus[i] == 1
let newtags .= ':' . buftags[i-1] . ':'
endif
let i += 1
endwhile
let newtags = substitute(newtags, '::',':','g')
call setline(a:line+1, repeat(' ',s:Starcount(a:line)+1) . newtags)
endwhile
if empty(s:GetTagList(a:line))
execute a:line+1 .'d'
execute a:line
endif
endfunction
function! s:UnconvertTags(line)
if s:IsTagLine(a:line+1)
normal J
endif
endfunction
function! <SID>GlobalUnconvertTags(state)
if exists('g:org_emacs_autoconvert') && (g:org_emacs_autoconvert != 0)
let s:save_cursor = getpos(".")
let s:last_changenr = a:state
mkview
normal A
g/^\*\+\s/call s:UnconvertTags(line("."))
silent! %s/^\(\s*\):\(DEADLINE\|SCHEDULED\|CLOSED\|CLOCK\|<\d\d\d\d-\d\d-\d\d\)/\1\2/
endif
endfunction
function! <SID>UndoUnconvertTags()
if exists('g:org_emacs_autoconvert') && (g:org_emacs_autoconvert != 0)
silent exec 'undo ' . s:last_changenr
silent undo
loadview
call setpos(".",s:save_cursor)
endif
endfunction
function! s:ConvertTags(line)
let tags = matchstr(getline(a:line), '\(:\S*:\)\s*$')
if tags ># ''
s/\s\+:.*:\s*$//
call append(a:line, repeat(' ',s:Starcount(a:line)+1) . tags)
endif
endfunction
function! <SID>GlobalConvertTags()
"if exists('g:org_emacs_autoconvert') && (g:org_emacs_autoconvert != 0)
let save_cursor = getpos(".")
g/^\*\+\s/call s:ConvertTags(line("."))
silent! %s/^\(\s*\)\(DEADLINE:\|SCHEDULED:\|CLOSED:\|CLOCK:\|<\d\d\d\d-\d\d-\d\d\)/\1:\2/
call setpos(".",save_cursor)
"endif
endfunction
function! s:GlobalFormatTags()
let save_cursor = getpos(".")
g/^\*\+\s/call s:FormatTags(line("."))
call setpos(".",save_cursor)
endfunction
function! s:FormatTags(line)
let tagmatch = matchlist(getline(a:line),'\(:\S*:\)\s*$')
if !empty(tagmatch)
let linetags = tagmatch[1]
s/\s\+:.*:\s*$//
" add newtags back in, including new tag
call setline(a:line,getline(a:line) . ' '
\ . repeat(' ', winwidth(0) - len(getline(a:line)) - len(linetags) - 15)
\ . linetags)
endif
endfunction
function! s:FCTest(line)
if foldclosed(a:line) != a:line
return a:line . ' --- ' . foldclosed(a:line)
endif
endfunction
function! OrgSequenceTodo(line,...)
if a:0 == 1
if a:1 ==? 'x'
let newtodo = ''
else
for item in b:v.todoitems
if item[0] ==? a:1
let newtodo = item
endif
endfor
endif
endif
let linetext = getline(a:line)
if (linetext =~ s:org_headMatch)
" get first word in line and its index in todoitems
let tword = matchstr(linetext,'\*\+\s\+\zs\S\+\ze')
if a:0 == 1
call s:ReplaceTodo(newtodo)
else
call s:ReplaceTodo()
endif
endif
endfunction
function! s:NextTodo(curtodo)
let curtodo = a:curtodo
" check whether word is in todoitems and make appropriate
" substitution
let j = -1
let newi = -1
let i = index(b:v.fulltodos,curtodo)
if i == -1
let i = 0
while i < len(b:v.fulltodos)
if type(b:v.fulltodos[i]) == type([])
let j = index(b:v.fulltodos[i],curtodo)
if j > -1
break
endif
endif
let i += 1
endwhile
endif
if i == len(b:v.fulltodos)-1
let newtodo = ''
else
if (i == len(b:v.fulltodos))
" not found, newtodo is index 0
let newi = 0
elseif (i >= 0)
let newi = i+1
endif
if type(b:v.fulltodos[newi]) == type([])
let newtodo = b:v.fulltodos[newi][0]
else
let newtodo = b:v.fulltodos[newi]
endif
endif
return newtodo
endfunction
function! s:PreviousTodo(curtodo)
let curtodo = a:curtodo
" check whether word is in todoitems and make appropriate
" substitution
let j = -1
let newi = -1
let i = index(b:v.fulltodos,curtodo)
if i == -1
let i = 0
while i < len(b:v.fulltodos)
if type(b:v.fulltodos[i]) == type([])
let j = index(b:v.fulltodos[i],curtodo)
if j > -1
break
endif
endif
let i += 1
endwhile
endif
"if i == len(b:v.fulltodos)-1
if i == 0
let newtodo = ''
else
if (i == len(b:v.fulltodos))
" not found, newtodo is index 0
let newi = len(b:v.fulltodos) - 1
elseif (i > 0)
let newi = i-1
endif
if type(b:v.fulltodos[newi]) == type([])
let newtodo = b:v.fulltodos[newi][0]
else
let newtodo = b:v.fulltodos[newi]
endif
endif
return newtodo
endfunction
function! OrgTodoDashboard(...)
let key = (a:0==1) ? a:1 : ''
let save_cursor = getpos('.')
let save_window = winnr()
if bufname("%") ==? ('__Agenda__')
let file = s:filedict[str2nr(matchstr(getline(line('.')), '^\d\d\d'))]
let lineno = str2nr(matchstr(getline(line('.')),'^\d\d\d\zs\d*'))
let buffer_lineno = s:ActualBufferLine(lineno,bufnr(file))
let b:v.todoitems = getbufvar(file,'v').todoitems
let b:v.todo_setup = getbufvar(file,'v').todo_setup
let props = s:GetProperties(buffer_lineno, 0, file)
let Replace_func = function('s:AgendaReplaceTodo')
else
exec s:OrgGetHead()
let props = s:GetProperties(line('.'),0)
let Replace_func = function('s:ReplaceTodo')
endif
if key ==# ''
echohl MoreMsg
echo " ================================="
echo " Todos defined in this " . (bufname("%") ==? ('__Agenda__') ? "heading's" : "" ) . " document are:"
echo " " . b:v.todo_setup
echo " ================================="
echo " Press key for a todo command:"
echo " ---------------------------------"
echo " f (or n) cycle current heading's todo Forward/Next"
echo " b (or p) cycle current heading's todo Backward/Previous"
echo " t mark current heading with initial 'unfinished' state"
echo " d mark current heading with main 'finished' state"
"if bufname("%") !=? ('__Agenda__')
let i = 1
for item in b:v.todoitems
echo ' ' . i . ' mark current heading as ' . item
let i += 1
endfor
"endif
echo " "
echohl Question
let key = nr2char(getchar())
redraw
endif
"let thisline = getline(line('.'))
"let curTodo = matchstr(thisline, '\*\+ \zs\S\+')
if key =~? 'f\|n'
call Replace_func()
elseif key =~? 'b\|p'
call Replace_func('todo-bkwd')
elseif key ==? 't'
"call Replace_func(b:v.todoitems[0])
call Replace_func('first-todo')
elseif key ==? 'd'
"let done_state = (type(b:v.fulltodos[-1])==type([])) ? b:v.fulltodos[-1][0] : b:v.fulltodos[-1]
"call Replace_func(done_state)
call Replace_func('first-done')
elseif key =~ '[1-9]'
call Replace_func(b:v.todoitems[key-1])
else
echo "No todo action selected."
endif
echohl None
exe save_window . 'wincmd w'
call setpos('.',save_cursor)
endfunction
function! s:AgendaReplaceTodo(...)
" wrapper to call OrgAgendaGetText to do todo operation
" OrgAgendaGetText does double duty (needs to be
" refactored) and both retrieves text from main buffer
" and handles todo replacements
if bufname('%') != '__Agenda__'
echo "Not in agenda, can't use AgendaReplaceTodo"
return
endif
if empty(b:v.heading_marks_dict)
" just mark and do current item
let b:v.heading_marks_dict[line('.')] = 1
endif
for item in sort(keys(b:v.heading_marks_dict), 's:ReverseSort')
" go to the line first, then process
exec item
let file = s:filedict[str2nr(matchstr(getline(line('.')), '^\d\d\d'))]
let b:v.fulltodos = getbufvar(file,'v').fulltodos
let b:v.todoitems = getbufvar(file,'v').todoitems
let todoword = matchstr(getline(line('.')), '.* \*\+ \zs\S\+')
if a:0 == 0
let newtodo = 'todo-fwd'
else
let newtodo = a:1
endif
if newtodo == 'todo-fwd'
let newtodo = s:NextTodo(todoword)
elseif newtodo == 'todo-bkwd'
let newtodo = s:PreviousTodo(todoword)
elseif newtodo == 'first-todo'
let newtodo = b:v.todoitems[0]
elseif newtodo == 'first-done'
let newtodo = (type(b:v.fulltodos[-1])==type([])) ? b:v.fulltodos[-1][0] : b:v.fulltodos[-1]
else
let newtodo = a:1
endif
call OrgAgendaGetText(1,newtodo)
execute 'sign unplace ' . item . ' buffer=' . bufnr('%')
endfor
let b:v.heading_marks_dict = {}
endfunction
function! s:ReplaceTodo(...)
"a:1 would be newtodo word
let save_cursor = getpos('.')
if getline(line('.'))[0] == '*'
exec s:OrgGetHead()
endif
let thisline = getline(line('.'))
if bufname("%") !=? '__Agenda__'
let todoword = matchstr(thisline, '\*\+ \zs\S\+')
else
let file = s:filedict[str2nr(matchstr(getline(line('.')), '^\d\d\d'))]
" fulltodos needed for s:NewTodo()
let b:v.fulltodos = getbufvar(file,'v').fulltodos
let b:v.todoitems = getbufvar(file,'v').todoitems
let todoword = matchstr(thisline, '.* \*\+ \zs\S\+')
endif
if a:0 == 0
let newtodo = 'todo-fwd'
else
let newtodo = a:1
endif
if newtodo == 'todo-fwd'
let newtodo = s:NextTodo(todoword)
elseif newtodo == 'todo-bkwd'
let newtodo = s:PreviousTodo(todoword)
elseif newtodo == 'first-todo'
let newtodo = b:v.todoitems[0]
elseif newtodo == 'first-done'
let newtodo = (type(b:v.fulltodos[-1])==type([])) ? b:v.fulltodos[-1][0] : b:v.fulltodos[-1]
else
let newtodo = a:1
endif
" if going to main done state check for repeater and change date if necessary
if (bufnr("%") != bufnr('Agenda')) && (newtodo =~ b:v.todoDoneMatch[11:])
let newtodo = s:CheckDateRepeaterDone(todoword, newtodo)
endif
let s:last_newtodo = newtodo " used to set agenda line in next pass from agenda
if newtodo ># ''
let newtodo .= ' '
endif
if (index(b:v.todoitems,todoword) >= 0)
if newtodo ># ''
let newline = substitute(getline(line(".")),
\ '\* ' . todoword.' ',
\ '\* ' . newtodo,'g')
else
let newline = substitute(getline(line(".")),
\ '\* ' . todoword.' ',
\ '\* ' . '','g')
endif
else
let newline = substitute(getline(line(".")),
\ '\zs\* \ze\S\+',
\ '\* ' . newtodo ,'g')
endif
call setline(line("."),newline)
if exists("*Org_after_todo_state_change_hook") && (bufnr("%") != bufnr('Agenda'))
let Hook = function("Org_after_todo_state_change_hook")
call Hook(line('.'),todoword,newtodo)
endif
call setpos('.',save_cursor)
endfunction
function! s:CheckDateRepeaterDone(state1,state2)
"check for date repeater on change of todo to done state
" and handle logging and resetting of date"
let newtodo = a:state2
let props = s:GetProperties(line('.'),0)
let repeat_pattern = '\d\d\d\d-\d\d-\d\d.*[ +.]+\d\+\S\+.*'
for dateprop in ['DEADLINE','SCHEDULED','TIMESTAMP']
let thisdate = get(props,dateprop)
if thisdate =~ repeat_pattern
"put in log note
call OrgConfirmDrawer("LOGBOOK")
let str = ":- State: " . printf('%.10s','"'.a:state2.'"') . " from: " . printf('%.10s','"'.a:state1.'"') .
\ ' [' . org#Timestamp() . ']'
call append(line("."), repeat(' ',len(matchstr(getline(line(".")),'^\s*'))) . str)
exec s:OrgGetHead()
let newtodo = b:v.todocycle[0]
"change date as appropriate
let basedate = matchstr(thisdate,'\d\d\d\d-\d\d-\d\d')
let cue = '+' . matchstr(thisdate,'+\d*[dwmy]')
if thisdate =~ ' +\d*[dwmy]'
let newdate = DateCueResult(cue,basedate)
elseif thisdate =~ '\.+\d*[dwmy]'
let newdate = DateCueResult(cue,org#Timestamp()[0:9])
elseif thisdate =~ '++\d*[dwmy]'
let newdate = DateCueResult(cue,basedate)
let i = 0
while newdate <= org#Timestamp()[0:9]
if i == 9
unsilent call confirm('Ten adjustments failed to bring to future date.')
break
endif
let newdate = DateCueResult(cue,newdate)
let i += 1
endwhile
endif
let mydow = calutil#dayname(newdate)
call s:SetProp(dateprop,'<' . newdate . ' ' . mydow . thisdate[14:] . '>')
" break as soon as one repeater is found
unsilent call confirm('Repeater date: entering log and resetting date.')
break
endif
endfor
return newtodo
endfunction
"Section Navigation Funcs
"
function! s:OrgSubtreeLastLine()
" Return the line number of the next head at same level, 0 for none
return s:OrgSubtreeLastLine_l(line("."))
endfunction
function! s:OrgSubtreeLastLine_l(line)
if a:line == 0
return line("$")
endif
let l:starthead = s:OrgGetHead_l(a:line)
let l:stars = s:Starcount(l:starthead)
let l:mypattern = substitute(b:v.headMatchLevel,'level', '1,'.l:stars, "")
let l:lastline = s:Range_Search(l:mypattern,'nW', line("$"), l:starthead)
" lastline now has NextHead on abs basis so return end of subtree
if l:lastline != 0
let l:lastline -= 1
else
let l:lastline = line("$")
endif
return l:lastline
endfunction
function! s:HasAncestorHeadOf(line,ancestor)
let ultimate = s:OrgUltimateParentHead_l(a:line)
if (a:line < a:ancestor) || (a:ancestor < ultimate)
let result = 0
elseif (a:line == a:ancestor)
let result = 1
else
let test_ancestor = s:OrgParentHead_l(a:line)
while 1
if (test_ancestor == a:ancestor)
let result = 1
break
elseif test_ancestor < ultimate
let result = 0
break
endif
let test_ancestor = s:OrgParentHead_l(test_ancestor)
endwhile
endif
return result
endfunction
function! s:OrgUltimateParentHead()
" Return the line number of the parent heading, 0 for none
return s:OrgUltimateParentHead_l(line("."))
endfunction
function! s:OrgUltimateParentHead_l(line)
" returns 0 for main headings, main heading otherwise
let l:starthead = s:OrgGetHead_l(a:line)
if s:Ind(l:starthead) > 1
return s:Range_Search('^* ','bnW',1,l:starthead)
else
return 0
endif
endfunction
function! s:OrgParentHead()
" Return the line number of the parent heading, 0 for none
return s:OrgParentHead_l(line("."))
endfunction
function! s:OrgParentHead_l(line)
" todo -- get b:v.levelstars in here
let l:starthead = s:OrgGetHead_l(a:line)
let l:parentheadlevel = s:Starcount(l:starthead) - b:v.levelstars
if l:parentheadlevel <= 0
return 0
else
let l:mypattern = substitute(b:v.headMatchLevel,'level',l:parentheadlevel,'')
return s:Range_Search(l:mypattern,'bnW',1,l:starthead)
endif
endfunction
function! s:Range_Search(stext, flags, ...)
" searches range, restores cursor to
" beginning position, and returns
" first occurrence of pattern
let save_cursor = getpos(".")
" a:1 and a:2 are stopline and startline
if a:0 == 2
let l:stopline = a:1
" go to startline
execute a:2
normal! $
elseif a:0 == 1
let l:stopline = a:1
else
let l:stopline = line("$")
endif
let l:result = search(a:stext, a:flags, l:stopline)
call setpos('.',save_cursor)
return l:result
endfunction
function! s:OrgGetHead()
return s:OrgGetHead_l(line("."))
endfunction
function! s:OrgGetHead_l(line)
if s:IsText(a:line)
return s:Range_Search(b:v.headMatch,'nb', 1, a:line)
else
return a:line
endif
endfunction
function! s:OrgPrevSiblingHead()
return s:OrgPrevSiblingHead_l(line("."))
endfunction
function! s:OrgPrevSiblingHead_l(line)
if s:Ind(a:line) > 0
let upperline = s:OrgParentHead_l(a:line)
else
let upperline = 0
endif
let sibline = s:OrgPrevHeadSameLevel_l(a:line)
if (sibline <= upperline)
let sibline = 0
endif
return sibline
endfunction
function! s:OrgNextSiblingHead()
return s:OrgNextSiblingHead_l(line("."))
endfunction
function! s:OrgNextSiblingHead_l(line)
if s:Ind(a:line) > 0
let lastline = s:OrgSubtreeLastLine_l(s:OrgParentHead_l(a:line))
else
let lastline = line("$")
endif
let sibline = s:OrgNextHeadSameLevel_l(a:line)
if (sibline > lastline)
let sibline = 0
endif
return sibline
endfunction
function! s:OrgNextHead()
" Return the line number of the next heading, 0 for none
return s:OrgNextHead_l(line("."))
endfunction
function! s:OrgNextHead_l(line)
return s:Range_Search(b:v.headMatch,'n', line("$"),a:line)
endfunction
function! s:OrgPrevHead()
" Return the line number of the previous heading, 0 for none
return s:OrgPrevHead_l(line("."))
endfunction
function! s:OrgPrevHead_l(line)
return s:Range_Search(b:v.headMatch,'nb', 1, a:line-1)
endfunction
function! s:OrgNextHeadSameLevel()
" Return the line number of the next head at same level, 0 for none
return s:OrgNextHeadSameLevel_l(line("."))
endfunction
function! s:OrgNextHeadSameLevel_l(line)
let level = s:Starcount(a:line)
let mypattern = substitute(b:v.headMatchLevel,'level', level, "")
let foundline = s:Range_Search(mypattern,'nW', line("$"), a:line)
if foundline < line ("$")
return foundline
else
if s:Starcount(foundline) > 0
return foundline
else
return 0
endif
endif
endfunction
function! s:OrgPrevHeadSameLevel()
" Return the line number of the previous heading, 0 for none
return s:OrgPrevHeadSameLevel_l(line("."))
endfunction
function! s:OrgPrevHeadSameLevel_l(line)
let l:level = s:Starcount(a:line)
let l:mypattern = substitute(b:v.headMatchLevel,'level', l:level, "")
let foundline = s:Range_Search(mypattern,'nbW', 1, a:line-1)
if foundline > 1
return foundline
else
if (s:Starcount(foundline) > 0) && (a:line != 1)
return 1
else
return 0
endif
endif
endfunction
function! s:OrgFirstChildHead()
" Return the line number of first child, 0 for none
return s:OrgFirstChildHead_l(line("."))
endfunction
function! s:OrgFirstChildHead_l(line)
let l:starthead = s:OrgGetHead_l(a:line)
let l:level = s:Starcount(l:starthead) + 1
let l:nexthead = s:OrgNextHeadSameLevel_l(l:starthead)
if l:nexthead == 0
let l:nexthead = line("$")
endif
let l:mypattern = substitute(b:v.headMatchLevel,'level', l:level, "")
return s:Range_Search(l:mypattern,'nW',l:nexthead, l:starthead)
endfunction
function! s:OrgLastChildHead()
" Return the line number of the last child, 0 for none
return s:OrgLastChildHead_l(line("."))
endfunction
function! s:OrgLastChildHead_l(line)
" returns line number of last immediate child, 0 if none
let l:starthead = s:OrgGetHead_l(a:line)
let l:level = s:Starcount(l:starthead) + 1
let l:nexthead = s:OrgNextHeadSameLevel_l(l:starthead)
if l:nexthead == 0
let l:nexthead = line("$")
endif
let l:mypattern = substitute(b:v.headMatchLevel,'level', l:level, "")
return s:Range_Search(l:mypattern,'nbW',l:starthead, l:nexthead)
endfunction
function! s:MyLastChild(line)
" Return the line number of the last decendent of parent line
let l:parentindent = s:Ind(a:line)
if s:IsText(a:line+1)
let l:searchline = s:NextLevelLine(a:line+1)
else
let l:searchline = a:line+1
endif
while s:Ind(l:searchline) > l:parentindent
let l:searchline = l:searchline+1
endwhile
return l:searchline-1
endfunction
function! s:NextVisibleHead(line)
" Return line of next visible heanding, 0 if none
let save_cursor = getpos(".")
while 1
let nh = s:OrgNextHead()
if (nh == 0) || s:IsVisibleHeading(nh)
break
endif
execute nh
endwhile
call setpos('.',save_cursor)
return nh
endfunction
function! s:FoldStatus(line)
" adds new heading or text level depending on type
let l:fc = foldclosed(a:line)
if l:fc == -1
let l:status = 'unfolded'
elseif l:fc > 0 && l:fc < a:line
let l:status = 'infold'
elseif l:fc == a:line
let l:status = 'foldhead'
endif
return l:status
endfunction
function! OrgEnterFunc()
let syn_items = synstack(line('.'),col('.'))
call map(syn_items, "synIDattr(v:val,'name')")
if (index(syn_items,'Org_Full_Link') >= 0) || ( index(syn_items,'Org_Half_Link') >= 0)
call FollowLink( OrgGetLink() )
else
call OrgNewHead('same')
endif
endfunction
function! OrgNewHead(type,...)
" adds new heading or text level depending on type
if a:0 == 1
normal 
endif
execute s:OrgGetHead()
let l:org_line = line(".")
let l:linebegin = matchlist(getline(line(".")),'^\(\**\s*\)')[1]
if s:IsText(line(".")) == 0
let l:lastline = s:OrgSubtreeLastLine()
if a:type ==? 'levelup'
let l:linebegin = substitute(l:linebegin,'^\*\{'.b:v.levelstars.'}','','')
elseif a:type ==? 'leveldown'
let l:linebegin = substitute(l:linebegin,'^\*',repeat('*',b:v.levelstars+1),'')
endif
call append( l:lastline ,l:linebegin)
execute l:lastline + 1
startinsert!
endif
return ''
endfunction
function! s:IsText(line)
" checks for whether line is any kind of text block
" test if line matches all-inclusive text block pattern
return (getline(a:line) !~ b:v.headMatch) && (a:line <= line('$'))
endfunction
function! s:NextLevelAbs(line)
" Return line of next heading
" in absolute terms, not just visible headings
let l:i = 1
" go down to next non-text line
while s:IsText(a:line + l:i)
let l:i = l:i + 1
"if (a:line + l:i) == line("$")
:" return 0
"endif
endwhile
return a:line + l:i
endfunction
function! s:NextLevelLine(line)
" Return line of next heading
let l:fend = foldclosedend(a:line)
if l:fend == -1
let l:i = 1
" go down to next non-text line
while s:IsText(a:line + l:i)
let l:i = l:i + 1
endwhile
return a:line + l:i
else
return l:fend+1
endif
endfunction
function! s:HasChild(line)
" checks for whether heading line has
" a sublevel
" checks to see if heading has a non-text sublevel
let nh = s:OrgNextHead_l(a:line)
if nh == 0
return 0
else
return (s:Ind(nh) > s:Ind(a:line))
endif
" if s:IsText(a:line + 1) &&
" \ (s:Ind(s:NextLevelLine(a:line+1)) > s:Ind(a:line))
" return 1
" elseif s:IsText(a:line + 1) == 0 &&
" \ (s:Ind(s:NextLevelLine(a:line)) > s:Ind(a:line))
" return 1
" else
" return 0
" endif
endfunction
function! s:DoFullCollapse(line)
let lastline = s:OrgSubtreeLastLine_l(a:line)
if lastline == a:line
return
else
while foldclosedend(a:line) < lastline
normal! zc
endwhile
endif
" make sure headline is not just
" text collapse
" test if line matches all-inclusive text block pattern
" while foldclosed(a:line) == -1 && (s:HasChild(a:line) || s:IsText(a:line+1))
" normal! zc
" endwhile
" if s:IsTextOnlyFold(a:line) && s:HasChild(a:line)
" normal! zc
" if s:IsTextOnlyFold(a:line) && s:HasChild(a:line)
" normal! zc
" if s:IsTextOnlyFold(a:line) && s:HasChild(a:line)
" normal! zc
" endif
" endif
" endif
endfunction
function! s:IsTextOnlyFold(line)
" checks for whether heading line has full fold
" or merely a text fold
"if s:IsText(a:line + 1) && (foldclosed(a:line + 1) == a:line)
if s:IsText(a:line + 1) && (foldclosedend(a:line) > 0)
\ && (s:Ind(foldclosedend(a:line)) <= s:Ind(a:line))
return 1
else
return 0
endif
endfunction
function! s:MaxVisIndent(headingline)
" returns max indent for
" visible lines in a heading's subtree
" used by ShowSubs
let l:line = a:headingline
let l:endline = s:OrgSubtreeLastLine()
"let l:endline = s:MyLastChild(l:line)
let l:maxi = s:Ind(l:line)
let l:textflag = 0
while l:line <= l:endline
if (s:Ind(l:line) > l:maxi) &&
\ ( foldclosed(l:line) == l:line
\ || foldclosed(l:line) == -1 )
let l:maxi = s:Ind(l:line)
if s:IsText(l:line)
let l:textflag = 1
endif
endif
let l:line = l:line + 1
endwhile
return l:maxi + l:textflag
endfunction
function! OrgShowLess(headingline)
" collapses headings at farthest out visible level
let l:maxi = s:MaxVisIndent(a:headingline)
let l:offset = l:maxi - s:Ind(a:headingline)
echo 'offset: ' . l:offset
if l:offset > 1
call s:ShowSubs(l:offset - 1,0)
elseif l:offset == 1
normal zc
"normal! zc
endif
endfunction
function! OrgShowMore(headingline)
" expands headings at furthest out
" visible level in a heading's subtree
let l:maxi = s:MaxVisIndent(a:headingline)
let l:offset = l:maxi - s:Ind(a:headingline)
if l:offset >= 0
call s:ShowSubs(l:offset + 1,0)
if l:maxi == s:MaxVisIndent(a:headingline)
"call OrgSingleHeadingText('expand')
endif
endif
endfunction
function! OrgShowSubs(number,withtext)
" used by comma-num mapping
" expands/collapses individual heading to level visibility equal to a:number
if getline(line('.'))[0] != '*'
exec s:OrgPrevHead()
endif
let cur_level = s:Ind(line('.')) - 1
if a:number > cur_level
let rel_level = a:number - cur_level
if rel_level >= 1
call s:ShowSubs(rel_level ,0)
endif
else
call s:DoFullCollapse(line('.'))
endif
normal ztkj
endfunction
function! s:ShowSubs(number,withtext)
" shows specif number of levels down from current
" heading, includes text
" or merely a text fold
let save_cursor = getpos(".")
call s:DoFullCollapse(line("."))
let l:start = foldclosed(line("."))
if l:start != -1
let l:end = foldclosedend(line("."))
exec "" . l:start . "," . l:end . "foldc!"
exec "normal! zv"
let to_level = 2
for to_level in range( 2 , a:number )
exec "" . l:start . "," . l:end . "foldo"
endfor
endif
if a:withtext == 0
call OrgSingleHeadingText('collapse')
endif
call setpos(".",save_cursor)
endfunction
" 2 args of start line num and direction ('up' or 'down')
"command -nargs=* OrgMoveLevel :call OrgMoveLevel(<f-args>,v:count1)
nmap <buffer> <localleader>,q :<C-U>call OrgMoveLevel(line('.'),'up',v:count1)<cr>
function! OrgMoveLevel(line, direction,...)
if (getline(a:line) !~ b:v.headMatch)
echo "Must be on a heading line to move subtrees."
return
endif
if a:0>=1
let mycount = a:1
else
let mycount = 1
endif
" move a heading tree up, down, left, or right
let lastline = s:OrgSubtreeLastLine_l(a:line)
if a:direction ==? 'up'
let l:headabove = a:line
let count_message = ''
for i in range( 1, mycount)
let lasthead = l:headabove
let l:headabove = s:OrgPrevSiblingHead_l(l:headabove)
if l:headabove > 0
let count_message = 'Moved up ' . i . ' levels.'
elseif i == 1
" break with no message here
break
else
let l:headabove = lasthead
if i <= mycount | let count_message .= ' No more siblings above.' | endif
break
endif
endfor
if l:headabove > 0
let l:lines = getline(line("."), lastline)
call s:DoFullCollapse(a:line)
silent normal! dd
call append(l:headabove-1,l:lines)
execute l:headabove
call s:ShowSubs(1,0)
echo count_message
else
echo "No sibling heading above in this subtree."
endif
elseif a:direction ==? 'down'
let l:headbelow = a:line
let count_message = ''
for i in range(1, mycount)
let lasthead = l:headbelow
let l:headbelow = s:OrgNextSiblingHead_l(l:headbelow)
if l:headbelow > 0
let count_message = 'Moved down ' . i . ' levels.'
elseif i == 1
" break with no message here
break
else
let l:headbelow = lasthead
if i <= mycount | let count_message .= ' No more siblings below.' | endif
break
endif
endfor
if l:headbelow > 0
let endofnext = s:OrgSubtreeLastLine_l(l:headbelow)
let lines = getline(line("."),lastline)
silent call append(endofnext,lines)
execute endofnext + 1
" set mark and go back to delete original subtree
normal ma
execute a:line
call s:DoFullCollapse(a:line)
silent normal! dd
normal g'a
call s:ShowSubs(1,0)
echo count_message
else
echo "No sibling below in this subtree."
endif
elseif a:direction ==? 'left'
if s:Ind(a:line) > 2
" first move to be last sibling
let movetoline = s:OrgSubtreeLastLine_l(s:OrgParentHead_l(a:line))
let lines = getline(line("."),lastline)
call append(movetoline,lines)
execute movetoline + 1
" set mark and go back to delete original subtree
normal ma
execute a:line
call s:DoFullCollapse(a:line)
silent exe 'normal! dd'
normal g'a
" now move tree to the left
normal ma
silent execute line(".") ',' . s:OrgSubtreeLastLine() . 's/^' . repeat('\*',b:v.levelstars) .'//'
call s:DoFullCollapse(a:line)
normal g'a
call s:ShowSubs(1,0)
execute line(".")
else
echo "You're already at main heading level."
endif
elseif a:direction ==? 'right'
if s:Ind(s:OrgPrevHead_l(a:line)) >= s:Ind(a:line)
execute a:line . ',' . lastline . 's/^\*/'.repeat('\*',b:v.levelstars+1).'/'
call s:DoFullCollapse(a:line)
execute a:line
call s:ShowSubs(1,0)
else
echo "Already at lowest level of this subtree."
endif
endif
endfunction
function! OrgNavigateLevels(direction)
" Move among headings
" direction: "up", "down", "right", "left","end", or 'home'
if s:IsText(line("."))
exec s:OrgGetHead()
return
endif
if s:Ind(line(".")) > 0
let lowerlimit = s:OrgParentHead()
let upperlimit = s:OrgSubtreeLastLine_l(lowerlimit)
else
let lowerlimit = 0
let upperlimit = line("$")
endif
if a:direction ==? "left"
let dest = s:OrgParentHead()
let msg = "At highest level."
elseif a:direction ==? "home"
let dest = s:OrgParentHead()
let msg = "At highest level."
elseif a:direction ==? "right"
let dest = s:OrgFirstChildHead()
let msg = (dest > 0 ? "Has subheadings, but none visible."
\ : "No more subheadings.")
elseif a:direction ==? 'end'
let dest = s:OrgLastChildHead()
let msg = (dest > 0 ? "Has subheadings, but none visible."
\ : "No more subheadings.")
elseif a:direction ==? 'up'
let dest = s:OrgPrevHeadSameLevel()
let msg = "Can't go up more here."
elseif a:direction ==? 'down'
let dest = s:OrgNextHeadSameLevel()
let msg = "Can't go down more."
endif
let visible = s:IsVisibleHeading(dest)
if (dest > 0) && visible && (dest >= lowerlimit) && (dest <= upperlimit)
execute dest
else
echo msg
endif
endfunction
function! OrgHeadingFirstText(headline)
exec a:headline + 1
let found = 0
while 1
let thisline = getline(line('.'))
if thisline =~ b:v.headMatch
break
else
if (thisline !~ s:remstring) && (thisline !~ b:v.dateMatch)
\ && (thisline !~ b:v.drawerMatch)
let found = line('.')
break
elseif line('.') == line('$')
break
endif
endif
exec line('.') + 1
endwhile
return found
endfunction
function! OrgUnfoldBodyText(headline)
if OrgHeadingFirstText(a:headline) > 0
normal zv
endif
endfunction
function! OrgExpandWithoutText(tolevel)
" expand all headings but leave Body Text collapsed
" tolevel: number, 0 to 9, of level to expand to
" expand levels to 'tolevel' with all body text collapsed
let l:startline = 1
let l:endline = line("$")
let l:execstr = "set foldlevel=" . string(a:tolevel )
"let l:execstr = "set foldlevel=" . (a:tolevel - 1)
exec l:execstr
call OrgBodyTextOperation(l:startline,l:endline,"collapse")
endfunction
function! s:OrgExpandSubtree(headline,...)
if a:0 > 0
let withtext = a:1
endif
let save_cursor = getpos(".")
call s:DoFullFold(a:headline)
"let end = foldclosedend(a:headline)
"normal! zO
"call OrgBodyTextOperation(a:headline, end, 'collapse')
call s:ShowSubs(3,withtext)
call setpos(".",save_cursor)
endfunction
function! s:OrgExpandHead(headline)
let save_cursor = getpos(".")
call s:DoFullFold(a:headline)
"let end = foldclosedend(a:headline)
"normal! zO
"call OrgBodyTextOperation(a:headline, end, 'collapse')
call s:ShowSubs(1,0)
while foldclosed(a:headline) != -1
normal! zo
endwhile
call setpos(".",save_cursor)
endfunction
function! s:DoFullFold(headline)
let save_cursor = getpos(".")
"normal! zo
call s:DoAllTextFold(a:headline)
let fend = foldclosedend(a:headline)
if ((fend > a:headline) && (s:Ind(fend+1) > s:Ind(a:headline)))
\ || (s:Ind(a:headline+1) > s:Ind(a:headline))
normal zc
endif
call setpos(".",save_cursor)
endfunction
function! s:OrgCycle(headline)
let save_cursor = getpos(".")
let end = foldclosedend(a:headline)
if (end>0) && (s:Ind(end+1) <= s:Ind(a:headline))
call s:OrgExpandHead(a:headline)
elseif ((end == -1) && (s:Ind(s:OrgNextHead_l(a:headline)) > s:Ind(a:headline))
\ && (foldclosed(s:OrgNextHead_l(a:headline)) > 0))
let nextsamelevel = s:OrgNextHeadSameLevel_l(a:headline)
let nextuplevel = s:OrgNextHeadSameLevel_l(s:OrgParentHead_l(a:headline))
if (nextsamelevel > 0) && (nextsamelevel > nextuplevel)
let endline = nextsamelevel
elseif nextuplevel > a:headline
let endline = nextuplevel
else
let endline = line('$')
endif
if b:v.cycle_with_text
call OrgBodyTextOperation(a:headline+1,endline,'expand')
else
call s:OrgExpandSubtree(a:headline,0)
endif
else
call s:DoFullFold(a:headline)
endif
call setpos(".",save_cursor)
endfunction
function! OrgCycle()
if getline(line(".")) =~ b:v.headMatch
call s:OrgCycle(line("."))
elseif getline(line(".")) =~ b:v.drawerMatch
normal! za
elseif getline(line('.')) =~ '^\s*|.*|\s*$'
" we're in a table, do tab and short circuit
exec "normal i\tl"
return
endif
" position to top of screen with cursor in col 0
"normal! z.
normal! ztkj
endfunction
let s:orgskipthirdcycle = 0
function! OrgGlobalCycle()
if getline(line('.')) =~ '^\s*|.*|\s*$'
"short circuit if we're in table
exec "normal i\<s-tab>l"
return
endif
if exists('w:sparse_on') && w:sparse_on
call s:ClearSparseTree()
endif
if (&foldlevel > 1) && (&foldlevel != b:v.global_cycle_levels_to_show)
call OrgExpandWithoutText(1)
elseif &foldlevel == 1
call OrgExpandWithoutText(b:v.global_cycle_levels_to_show)
"elseif (&foldlevel > 1) && ( s:orgskipthirdcycle == 0 )
" let s = getpos('.')
" g/^\*\+ /call OrgUnfoldBodyText(line('.'))
" call setpos('.',s)
" let s:orgskipthirdcycle = 1
else
let save_cursor = getpos('.')
set foldlevel=9999
silent exec 'g/' . b:v.drawerMatch . '/normal! zc'
let s:orgskipthirdcycle = 0
call setpos('.',save_cursor)
endif
endfunction
function! s:LastTextLine(headingline)
" returns last text line of text under
" a heading, or 0 if no text
let l:retval = 0
if s:IsText(a:line + 1)
let l:i = a:line + 1
while s:IsText(l:i)
let l:i = l:i + 1
endwhile
let l:retval = l:i - 1
endif
return l:retval
endfunction
function! s:ShowSynStack()
for id in synstack(line("."),col("."))
echo synIDattr(id,"name")
endfor
endfunction
function! s:SignList()
let signlist = ''
redir => signlist
silent execute "sign list"
redir END
return split(signlist,'\n')
endfunction
function! s:DeleteSigns()
" first delete all placed signs
sign unplace *
let signs = s:SignList()
for item in signs
silent execute "sign undefine " . matchstr(item,'\S\+ \zs\S\+\ze ')
endfor
sign define piet text=>>
sign define fbegin text=>
sign define fend text=<
sign define marked text=> linehl=Org_Marked
endfunction
function! s:GetPlacedSignsString(buffer)
let placedstr = ''
redir => placedstr
silent execute "sign place buffer=".a:buffer
redir END
return placedstr
endfunction
function! s:GetProperties(hl,withtextinfo,...)
let save_cursor = getpos(".")
if a:0 >=1
let curtab = tabpagenr()
let curwin = winnr()
" optional args are: a:1 - lineno, a:2 - file
call org#LocateFile(a:1)
endif
let datesdone = 0
let result1 = {}
let result = {}
let linetext = getline(a:hl)
if linetext[0] == '*'
let hl = a:hl
else
let hl = s:OrgGetHead_l(a:hl)
let linetext = getline(hl)
endif
let result1['LINE'] = hl
let result1['LEVEL'] = s:Ind(hl) - 1
"let linetext = getline(hl)
let result1['ITEM'] = linetext
let result1['FILE'] = expand("%:t")
" get date on headline, if any
if linetext =~ b:v.dateMatch
let result1['ld'] = matchlist(linetext,b:v.dateMatch)[1]
endif
if (getline(hl+1) =~ b:v.tagMatch) && (getline(hl+1) !~ b:v.drawerMatch)
let result1['TAGS'] = matchstr(getline(hl+1),b:v.tagMatch)
endif
if linetext =~ b:v.todoMatch
let result1['TODO'] = matchstr(linetext,b:v.todoMatch)
else
let result1['TODO'] = ''
endif
let line = hl + 1
"let firsttext=0
while 1
let ltext = getline(line)
if ltext =~ b:v.propMatch
let result = s:GetPropVals(line+1)
elseif (ltext =~ '^\s*:\s*CLOCK')
" do nothing
elseif (ltext !~ s:block_line) || (ltext =~ b:v.headMatch)
call extend(result, result1)
if datesdone
call extend(result, dateresult)
endif
let result['BLOCK_END'] = line - 1
break
elseif (ltext =~ b:v.dateMatch) && !datesdone
let dateresult = s:GetDateVals(line)
let datesdone = 1
" no break, go back around to check for props
"elseif (ltext =~ '^\s*$') || (ltext =~ '^\s*:\s*CLOCK')
endif
let line += 1
endwhile
" *****************************************
" get inherited properties
if s:include_inherited_props == 1
for item in b:v.org_inherited_properties
if index(keys(result), item) == -1
let result[item] = s:IProp(hl , item)
endif
endfor
endif
" *****************************************
" get last line
if a:withtextinfo
"let result['tbegin'] = line
let result['TEND'] = s:OrgNextHead_l(hl) - 1
endif
if a:0 >= 1
execute "tabnext ".curtab
execute curwin . "wincmd w"
endif
call setpos(".",save_cursor)
"debugging
let g:org_result = result
return result
endfunction
function! s:GetDateVals(line)
"result is dict with all date vals
let myline = a:line
let result = {}
while 1
let ltext = getline(myline)
let mtest1 = '<\zs'.b:v.dateMatch.'.*\ze>'
let mtest2 = '\[\zs'.b:v.dateMatch.'.*\ze\]'
if ltext =~ mtest1
"let mymatch = matchlist(ltext, '.\{-}\(<\d\d\d\d-\d\d-\d\d\) \S\S\S\( \d\d:\d\d\)*')
"let mydate = mymatch[1] . mymatch[2] . '>'
let mymatch = '^\s*\(:DEADLINE:\|:SCHEDULED:\|:CLOSED:\|:<\)\s*\zs.*'
let mydate = matchstr(ltext,mymatch)
let mydate = (mydate[0]=='<') ? mydate[1:-2] : mydate[:-2]
if ltext =~ 'DEADLINE'
let dtype = 'DEADLINE'
elseif ltext =~ 'SCHEDULED'
let dtype = 'SCHEDULED'
elseif ltext =~ 'CLOSED'
let dtype = 'CLOSED'
else
let dtype = 'TIMESTAMP'
endif
elseif ltext =~ mtest2
let mydate = matchstr(ltext, mtest2)
"let mydate = substitute(ltext, '\(\[\d\d\d\d-\d\d-\d\d\) \S\S\S\( \d\d:\d\d\)*','\1\2','')
let dtype = 'TIMESTAMP_IA'
else
break
endif
try
"only add if first of dtype encountered
if get(result,dtype) == 0
let result[dtype] = mydate
endif
catch /^Vim\%((\a\+)\)\=:E/
endtry
let myline += 1
endwhile
return result
endfunction
function! s:GetPropVals(line)
"result is dict with all prop vals
let myline = a:line
let result = {}
while 1
let ltext = getline(myline)
if ltext =~ b:v.propvalMatch
let mtch = matchlist(ltext, b:v.propvalMatch)
" mtch[1] is now property, mtch[2] is its value
try
let result[toupper(mtch[1])] = mtch[2]
catch /^Vim\%((\a\+)\)\=:E/
endtry
else
break
endif
let myline += 1
endwhile
return result
endfunction
function! s:RedoTextIndent()
set fdm=manual
set foldlevel=9999
exec 1
let myindent = 0
while line(".") < line("$")
let line = getline(line("."))
if matchstr(line,'^\*\+') ># ''
let myindent = len(matchstr(line,'^\*\+')) + g:org_indent_from_head
normal j
else
let text = matchstr(line,'^ *\zs.*')
let spaces = len(matchstr(line,'^ *'))
if (spaces != (myindent + 1)) && (text != '')
call setline(line("."),repeat(' ',myindent+1) . text)
endif
normal j
endif
endwhile
exec 1
set fdm=expr
endfunction
function! s:LoremIpsum()
let lines = ["Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?","At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."]
return split(lines[s:Random(3)-1],'\%70c\S*\zs \ze')
endfunction
"Section A New Section Here
function! s:Random(range)
"returns random integer from 1 to range
return (Rndm() % a:range) + 1
endfunction
function! s:RandomDate()
let date = string((2009 + s:Random(3) - 1)).'-'.s:Pre0(s:Random(12)).'-'.s:Pre0(s:Random(28))
let dstring = ''
if s:Random(3) == 3
let dstring = date. ' ' . calutil#dayname(date)
else
let dstring = date. ' ' . calutil#dayname(date).' '.s:Pre0(s:Random(23)).':'.s:Pre0((s:Random(12)-1)*5)
endif
if s:Random(6) == 6
let dstring .= ' +'.s:Random(4).['d','w','m'][s:Random(3)-1]
endif
return '<'.dstring.'>'
"if a:date_type != ''
" call s:SetProp(a:date_type,date)
"else
" silent execute "normal A".date
"endif
endfunction
function! s:SetRandomDate(...)
call s:OrgGetHead()
if a:0 == 1
let date_type = a:1
else
let date_type = ['DEADLINE','TIMESTAMP','SCHEDULED'][s:Random(3)-1]
endif
if date_type != ''
call s:SetProp(date_type,s:RandomDate())
else
let hl = line('.')
let dmatch = match(getline(hl),'\s*<\d\d\d\d-\d\d-\d\d')
if dmatch > 0
let dmatch = dmatch - 1
call setline(hl,getline(hl)[:dmatch])
endif
let newd = s:RandomDate()
execute hl
execute "normal A ". newd
endif
endfunction
function! s:SetRandomTodo()
let newtodo = b:v.todoitems[s:Random(3)-1]
if index(b:v.todoitems,matchstr(getline(line('.')),'^\*\+ \zs\S*\ze ')) >= 0
call setline(line('.'),matchstr(getline(line('.')),'^\*\+ ') . newtodo .
\ ' '. matchstr(getline(line('.')),'^\*\+ \S* \zs.*'))
else
call setline(line('.'),matchstr(getline(line('.')),'^\*\+ ') . newtodo .
\ ' '. matchstr(getline(line('.')),'^\*\+ \zs.*'))
endif
endfunction
function! s:UpdateHeadlineSums()
g/^\s*:TOTALCLOCKTIME/d
call OrgMakeDict()
let g:tempdict = {}
g/^\*\+ /let g:tempdict[line('.')] = b:v.org_dict.SumTime(line('.'),'ITEMCLOCKTIME')
let items = sort(map(copy(keys(g:tempdict)),"str2nr(v:val)"),'s:NumCompare')
let i = len(items) - 1
while i >= 0
if g:tempdict[items[i]] != '0:00'
call s:SetProp('TOTALCLOCKTIME',g:tempdict[items[i]],items[i])
endif
let i = i-1
endwhile
endfunction
function! s:IProp(headline,property)
let prop = a:property
let parent = s:OrgParentHead_l(a:headline)
if parent == 0
return get(b:v.org_inherited_defaults,prop)
else
return s:GetProperties(parent,0)[prop]
endif
endfunction
function! OrgMakeDictInherited(...)
let get_tags = ((a:0==1) && (a:1 =='get_tags_too')) ? 1 : 0
if (b:v.last_idict_time >= getftime(expand('%:p')) && (&modified==0))
" now check and return if last run had tags or this run doesn't need them
if (b:v.last_idict_with_tags == 1) || (get_tags == 0)
return
endif
endif
let b:v.last_idict_time = localtime()
let b:v.last_idict_with_tags = get_tags
if s:OrgVal('g:org_save_when_searched') > 0 | write! | endif
let b:v.org_dict = {}
call OrgProcessConfigLines()
let b:v.org_dict = {'0':{'c':[],'CATEGORY':b:v.org_inherited_defaults['CATEGORY'] }}
function! b:v.org_dict.iprop(ndx,property) dict
let prop = a:property
let ndx = a:ndx
let result = get(self[ndx] , prop,'')
if (result ==# '') && (ndx != 0)
"recurse up through parents in tree
let result = b:v.org_dict.iprop(self[ndx].parent,prop)
endif
return result
endfunction
execute 1
let next = 1
if s:IsText(line('.'))
let next = s:OrgNextHead()
endif
while next > 0
execute next
if getline(line('.'))[1] ==? ' '
let parent = 0
else
let parent = s:OrgParentHead()
endif
let b:v.org_dict[line('.')] = {'parent': parent}
let next = s:OrgNextHead()
endwhile
" parent properties assigned above, now explicity record CATEGORY for
" any headlines where CATEGORY won't be inherited
if get_tags == 0
silent execute 'g/^\s*:CATEGORY:/let b:v.org_dict[s:OrgGetHead()].CATEGORY = matchstr(getline(line(".")),":CATEGORY:\\s*\\zs.*")'
else
silent execute 'g/^\s*:CATEGORY:/let b:v.org_dict[s:OrgGetHead()].CATEGORY = matchstr(getline(line(".")),":CATEGORY:\\s*\\zs.*")'
silent g/^\*\+\s*\S/call s:GetBasicMeta(line('.'))
endif
endfunction
function! s:GetBasicMeta(line)
"let b:v.org_dict[a:line].CATEGORY = matchstr(getline(a:line),":CATEGORY:\\s*\\zs.*")
let this_line = getline(a:line)
let todo = matchstr(this_line,b:v.todoMatch)
"let b:v.org_dict[a:line].TODO = matchstr(getline(a:line),b:v.todoMatch)
if s:IsTagLine(a:line + 1)
let tags = matchstr(getline(a:line+1),'^\s*\zs.*')
else
let tags = ''
endif
let b:v.org_dict[a:line].props = {'ITEM': this_line,'TODO':todo,'TAGS':tags}
endfunction
function! OrgMakeDict()
if (b:v.last_dict_time >= getftime(expand('%:p')) && (&modified==0))
return
endif
" save new dict time to use in future searches
let b:v.last_dict_time = localtime()
"let b:v.org_dict = {}
"save buffer changes since last_dict
if s:OrgVal('g:org_save_when_searched') > 0 | write! | endif
" and recreate the dict
call OrgMakeDictInherited()
function! b:v.org_dict.SumTime(ndx,property) dict
let prop = a:property
let result = get(self[a:ndx].props , prop,'0:00')
" now recursion down the subtree of children in c
for item in self[a:ndx].c
let result = s:AddTime(result,b:v.org_dict.SumTime(item,prop))
endfor
return result
endfunction
function! b:v.org_dict.Sum(ndx,property) dict
let prop = a:property
let result = get(self[a:ndx].props , prop)
" now recursion down the subtree of children in c
for item in self[a:ndx].c
let result += b:v.org_dict.Sum(item,prop)
endfor
return result
endfunction
execute 1
let next = 1
if s:IsText(line('.'))
let next = s:OrgNextHead()
endif
while next > 0
execute next
let b:v.org_dict[line('.')].c = []
let b:v.org_dict[line('.')].props = s:GetProperties(line('.'),1)
let parent = b:v.org_dict[line('.')].parent
call add(b:v.org_dict[parent].c ,line('.'))
let next = s:OrgNextHead()
endwhile
endfunction
function! s:ClearSparseTreeOld()
set fdm=manual
silent exe '%s/^*x//'
silent exe 'undojoin | %s/^*o//'
"g/^*x/call substitute(getline(line(".")),'^*x',''))
"g/^*o/call substitute(getline(line(".")),'^*o',''))
call clearmatches()
set fdm=expr
echo "sparse tree view cleared"
endfunction
function! s:SparseTreeRun(term)
call s:ClearSparseLists()
let w:sparse_on = 1
execute 'g/' . a:term . '/call add(b:v.sparse_list,line("."))'
call s:SparseTreeDoFolds()
call clearmatches()
let g:org_first_sparse=1
let b:v.signstring= s:GetPlacedSignsString(bufnr("%"))
set fdm=expr
set foldlevel=0
let g:org_first_sparse=1
execute 'let @/ ="' . a:term .'"'
execute 'g/' . a:term . '/normal zv'
set hlsearch
execute 1
endfunction
function! s:SparseTreeDoFolds()
let i = len(b:v.sparse_list) - 1
while i >= 0
"if b:v.sparse_list[i] + g:org_sparse_lines_after > line("$")
if b:v.sparse_list[i] + 10 > line("$")
call remove(b:v.sparse_list, i) "insert(b:v.fold_list,0)
let i -= 1
continue
"elseif (i>0) && (b:v.sparse_list[i] < b:v.sparse_list[i-1] + g:org_sparse_lines_after)
elseif (i>0) && (b:v.sparse_list[i] < b:v.sparse_list[i-1] + 10)
call remove(b:v.sparse_list, i) "insert(b:v.fold_list,0)
let i -= 1
continue
else
let phead = s:OrgUltimateParentHead_l(b:v.sparse_list[i])
if phead >= 1
call insert(b:v.fold_list,phead-1)
else
" match is already on level 1 head
call insert(b:v.fold_list,b:v.sparse_list[i]-1)
endif
endif
let i -= 1
endwhile
"call map(b:v.sparse_list,"v:val + g:org_sparse_lines_after")
call map(b:v.sparse_list,"v:val + 10")
call insert(b:v.sparse_list, 1)
call add(b:v.fold_list, line("$"))
" sign method to potentially supersede list based method above
call s:DeleteSigns()
for item in b:v.sparse_list
execute "sign place " . item ." line=".item." name=fbegin buffer=".bufnr("%")
endfor
for item in b:v.fold_list
execute "sign place " . item ." line=".item." name=fend buffer=".bufnr("%")
endfor
let s:sparse_lines = {}
for item in b:v.sparse_list
let s:sparse_lines[item] = 1
let s:sparse_lines[item-1] = 1
endfor
for item in b:v.fold_list
let s:sparse_lines[item] = 1
endfor
" FoldTouch below instead of fdm line above to save time
" updating folds for just newly changed foldlevel lines
"call s:FoldTouch()
endfunction
function! s:ClearSparseLists()
" mylist with lines of matches
let b:v.sparse_list = []
" foldlist with line before previous level 1 parent
let b:v.fold_list = []
let b:v.sparse_heads = []
endfunction
function! s:ClearSparseTree()
" mylist with lines of matches
let w:sparse_on = 0
let b:v.sparse_list = []
" foldlist with line before previous level 1 parent
let b:v.fold_list = []
set fdm=expr
set foldlevel=1
execute 1
endfunction
function! s:FoldTouch()
" not used right now, since speed increase over
" set fdm=expr is uncertain, and was having problems
" in cleanly undoing it.
"
" touch each line in lists to update their fold levels
let i = 0
while i < len(b:v.sparse_list)
execute b:v.sparse_list[i]
" insert letter 'b' to force level update and then undo
silent execute "normal! ib"
silent execute "normal! u"
execute b:v.fold_list[i]
silent execute "normal! ib"
silent execute "normal! u"
let i += 1
endwhile
endfunction
function! s:OrgIfExpr()
let mypattern = ''
" two wrapper subst statements around middle
" subst are to make dates work properly with substitute/split
" operation
let ifstring_list = [[]]
let test_str = g:org_search_spec
if test_str[0] !~ '[+-]'
let test_str = '+' . test_str
endif
let ndx=0
let result_if_list = []
"try
while 1
" text string
" curly bracket reg ex string
" numeric comparison
" single operand -- TAG or TODO
let m = matchlist(test_str,'^\(|'
\ . '\|[+-]\w\{-}[!<>\=]=*".\{-}"'
\ . '\|[+-]\w\{-}[!\=]=*{.\{-}}'
\ . '\|[+-]\w\{-}[=<>!]=*[0-9+-.][0-9.]*'
\ . '\|[+-]\w*\)'
\ . '\(.*\)')
if m[1] == '|'
call add(ifstring_list,[])
let ndx += 1
let test_str = m[2]
if test_str !~ '+\|-'
let test_str = '+' . test_str
endif
elseif m[1] ># ''
call add(ifstring_list[ndx],m[1])
let test_str = m[2]
if test_str == ''
break
endif
else
break
endif
endwhile
for ifstr in ifstring_list
let b:v.my_if_list = ifstr
let ifexpr = ''
" okay, right now we have split list with each item prepended by + or -
" now change each item to be a pattern match equation in parens
" e.g.,'( prop1 =~ propval) && (prop2 =~ propval) && (thisline =~tag)
let i = 0
"using while structure because for structure doesn't allow changing
" items?
while i < len(b:v.my_if_list)
let item = b:v.my_if_list[i]
if item[0] !~ '+\|-'
let item = '+' . item
endif
" Propmatch has '=' sign and something before and after
if item =~ 'TEXT=\S.*'
let mtch = matchlist(item[1:],'\(\S.*\)=\(\S.*\)')
let b:v.my_if_list[i] = "(s:Range_Search('" . mtch[2][1:-2] . "','nbW',"
let b:v.my_if_list[i] .= 'tbegin,tend)> 0)'
let i += 1
" loop to next item
continue
endif
if item =~ '\S.*[=><]\S.*'
if item =~ '[^<>!]=\\('
let item = substitute(item,'=','=~','')
elseif item =~ '[^!]={'
let item = substitute(item,'[^!]\zs=','=~','')
let item = substitute(item,'{','"','')
let item = substitute(item,'}','"','')
elseif item =~ '!={'
let item = substitute(item,'!=','!~','')
let item = substitute(item,'{','"','')
let item = substitute(item,'}','"','')
elseif item =~ '[^<>!]=[^=]'
let item = substitute(item,'=','==','')
endif
let pat = '\(\S\{-}\)\(==\|=\~\|!\~\|>=\|<=\|!=\|<\|>\)\(\S.*\)'
let mtch = matchlist(item[1:],pat)
let mtch[1] = toupper(mtch[1])
if mtch[3] =~ '^[+\-0-9.][0-9.]*$'
" numeric comparison
let b:v.my_if_list[i] = (item[0]=='-' ? '!' : '') . '(get(lineprops,"' . mtch[1] . '") ' . mtch[2]. mtch[3] . ')'
else
" string comparison
let rightside="'".mtch[3][1:-2]."'"
let b:v.my_if_list[i] = (item[0]=='-' ? '!' : '') . '(get(lineprops,"' . mtch[1] . '","") ' . mtch[2]. rightside. ')'
" line below is addd on to exclude headings not
" having an entry at all from the comparison
" \ . '&& (get(lineprops,"' . mtch[1] . '","") != "")'
endif
let i += 1
" loop to next item
continue
endif
" it must be a todo or tag item
if item[0] ==? '+'
let op = '=~'
elseif item[0] ==? '-'
let op = '!~'
endif
" if it's in todoitems assume it's a todo search item, not a tag
if index(b:v.todoitems,item[1:]) >= 0
let item = '(lineprops.TODO ' . op . " '" . item[1:] . "')"
"let item = '(lineprops.TODO ' . op . " '^\\*\\+\\s*" . item[1:] . "')"
let b:v.my_if_list[i] = item
elseif item[1:] =~? 'UNFINISHED_TODO\|UNDONE_TODO'
let item = '(lineprops.TODO ' . op . " '" . b:v.todoNotDoneMatch[11:] . "')"
let b:v.my_if_list[i] = item
elseif item[1:] =~? 'FINISHED_TODO\|DONE_TODO'
let item = '(lineprops.TODO ' . op . " '" . b:v.todoDoneMatch[11:] . "')"
let b:v.my_if_list[i] = item
elseif item[1:] ==? 'ANY_TODO'
let item = '(lineprops.TODO ' . op . " '" . b:v.todoMatch[11:] . "')"
let b:v.my_if_list[i] = item
else
"not a todo so we treat it as a tag item
let item = '(get(lineprops,"TAGS","") ' . op . " ':" . item[1:] . ":')"
let b:v.my_if_list[i] = item
endif
let i += 1
endwhile
let i = 0
let b:v.check1 = b:v.my_if_list
let ifexpr = ''
while i < len(b:v.my_if_list)
let ifexpr .= b:v.my_if_list[i]
if i < len(b:v.my_if_list) - 1
let ifexpr .= ' && '
endif
let i += 1
endwhile
"return ifexpr
call add(result_if_list, ifexpr)
endfor
" let succeeded = 1
"finally
" if !exists('succeeded')
" return []
" else
return result_if_list
" endif
endtry
endfunction
function! s:CheckIfExpr(line,ifexpr,...)
" this is 'ifexpr' eval func used for agenda date searches
let headline = s:OrgGetHead_l(a:line)
" 0 arg is to not get start and end line numbers
let lineprops=s:GetProperties(headline,0)
" _thisline_ is variable evaluated in myifexpr
let thisline = getline(headline)
if s:IsTagLine(headline + 1)
let thisline .= ' ' . getline(headline+1)
endif
let result = 0
for item in a:ifexpr
if eval(item) == 1
let result = 1
break
endif
endfor
return result
endfunction
function! FileDict()
return s:filedict
endfunction
function! s:OrgIfExprResults(ifexpr,...)
" ifexpr has single compound expression that will evaluate
" as true only for desired lines
let sparse_search = 0
if a:0 > 0
let sparse_search = a:1
endif
"let myifexpr = a:ifexpr
execute 1
if getline(line('.'))!~ '^\*\+ '
let headline = s:OrgNextHead()
else
let headline = 1
endif
let g:checkexpr = a:ifexpr
while 1
if headline > 0
execute headline
" _thisline_ is variable evaluated in myifexpr
let thisline = getline(headline)
if s:IsTagLine(headline + 1)
let thisline .= ' ' . getline(headline+1)
endif
" lineprops is main variable tested in 'ifexpr'
" expression that gets evaluated
"let lineprops = s:GetProperties(headline,1)
let lineprops = b:v.org_dict[headline].props
for if_item in a:ifexpr
" next line is to fix for text area search
" now that we can reference tbegin and tend
let myifexpr = substitute(if_item,'\cTBEGIN,TEND',get(lineprops,'LINE') .','. get(lineprops,'TEND'),"")
"
"******** eval() is what does it all ***************
if eval(myifexpr)
if sparse_search
let keyval = headline
else
"let keyval = s:PrePad(index(s:agenda_files_copy, lineprops.file . '.org'),3,'0') . s:PrePad(headline,5,'0')
"let keyval = s:PrePad(lineprops.file,3,'0') . s:PrePad(headline,5,'0')
let keyval = s:PrePad(s:filenum,3,'0') . s:PrePad(headline,5,'0')
endif
let g:adict[keyval]=lineprops
if !exists('g:adict[keyval].CATEGORY')
let g:adict[keyval].CATEGORY = b:v.org_dict.iprop(headline,'CATEGORY')
endif
break
endif
endfor
normal l
let headline = s:OrgNextHead()
else
break
endif
endwhile
endfunction
function! s:MakeResults(search_spec,...)
let s:filedict = copy(g:agenda_files)
let sparse_search = 0
if a:0 > 0
let sparse_search = a:1
endif
let save_cursor = getpos(".")
"let curfile = substitute(expand("%"),' ','\\ ','g')
let curfile = substitute(expand("%:p"),' ','\\ ','g')
let curtab = tabpagenr()
let curwin = winnr()
let g:org_search_spec = a:search_spec
let g:org_todoitems=[]
let g:adict = {}
let g:datedict = {}
let s:agenda_files_copy = copy(g:agenda_files)
" fix so copy doesn't have full path. . .
"call map(s:agenda_files_copy, 'matchstr(v:val,"[\\/]") > "" ? matchstr(v:val,"[^/\\\\]*$") : v:val')
if sparse_search
call OrgMakeDict()
let ifexpr = s:OrgIfExpr()
call s:OrgIfExprResults(ifexpr,sparse_search)
else
let g:in_agenda_search = 1
for file in g:agenda_files
"execute 'tab drop ' . file
call org#LocateFile(file)
call org#SaveLocation()
" let bnum = bufnr(file)
" if bnum == -1
" execute 'tabedit ' . file
" else
" execute 'b' . bnum
" endif
let s:filenum = index(g:agenda_files,file)
if g:org_search_spec =~ '[<>\=!]'
call OrgMakeDict()
else
" it's just todos and/or tags
call OrgMakeDictInherited('get_tags_too')
endif
let ifexpr = s:OrgIfExpr()
let g:org_todoitems = extend(g:org_todoitems,b:v.todoitems)
call s:OrgIfExprResults(ifexpr,sparse_search)
call org#RestoreLocation()
endfor
unlet g:in_agenda_search
"call org#LocateFile(curfile)
execute 'tabnext ' . curtab
execute curwin . 'wincmd w'
endif
call setpos(".",save_cursor)
endfunction
function! s:DaysInMonth(date)
let month = str2nr(a:date[5:6])
let year = str2nr(a:date[0:3])
if (month == 2) && (year % 4)
let days = 28
elseif month == 2
let days = 29
elseif index([1,3,5,7,8,10,12],month) >= 0
let days = 31
else
let days = 30
endif
return days
endfunction
function! s:MakeAgenda(date,count,...)
if a:0 >= 1
let g:org_search_spec = a:1
else
let g:org_search_spec = ''
endif
let as_today = ''
if a:0 >= 2
let as_today = a:2
endif
"call org#SaveLocation()
let curtab = tabpagenr()
let curwin = winnr()
let l:count = a:count
if l:count ==? 'd' | let l:count = 1 | endif
if l:count ==? 'w'
let g:agenda_startdate = calutil#cal(calutil#jul(a:date) - calutil#dow(a:date))
let g:org_agenda_days=7
elseif l:count ==? 'm'
let g:agenda_startdate = a:date[0:7].'01'
let g:org_agenda_days = s:DaysInMonth(a:date)
elseif l:count ==? 'y'
let g:agenda_startdate = a:date[0:3].'-01-01'
let g:org_agenda_days = ( a:date[0:3] % 4 == 0 ) ? 366 : 365
else
let g:agenda_startdate = a:date
let g:org_agenda_days = l:count
endif
if l:count == 1 | let as_today = g:agenda_startdate | endif
let g:adict = {}
let s:filedict = copy(g:agenda_files)
let s:agenda_files_copy = copy(g:agenda_files)
let g:datedict = {}
call s:MakeCalendar(g:agenda_startdate,g:org_agenda_days)
let g:in_agenda_search=1
for file in g:agenda_files
call org#LocateFile(file)
call org#SaveLocation()
" for now g:org_search_spec is limited to tags and
" todo prop which are part of OrgMakeDictInherited
" If ever want to expand to general props can
" add OrgMakeDict()
call OrgMakeDictInherited()
let s:filenum = index(g:agenda_files,file)
let t:agenda_date=a:date
if as_today ># ''
call s:GetDateHeads(g:agenda_startdate,g:org_agenda_days,as_today)
else
call s:GetDateHeads(g:agenda_startdate,g:org_agenda_days)
endif
call org#RestoreLocation()
endfor
unlet g:in_agenda_search
"call org#RestoreLocation()
exec 'tabnext ' . curtab
exec curwin . 'wincmd w'
endfunction
function! s:NumCompare(i1, i2)
return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
endfunc
function! OrgRunSearch(search_spec,...)
"set mouseshape-=n:busy,v:busy,i:busy
if bufnr('Calendar') > 0
execute 'bw!' . bufnr('Calendar')
endif
try
if bufnr('__Agenda__') >= 0
"bwipeout __Agenda__
endif
let g:agenda_head_lookup={}
let sparse_search = 0
let search_type = ''
if a:0 > 0
if a:1 == 1
let sparse_search = a:1
else
let search_type=a:1
endif
endif
let g:adict={}
let g:agenda_date_dict={}
if !exists("g:agenda_files") || (g:agenda_files == [])
if has('dialog_con') || has('dialog_gui')
unsilent call confirm("No agenda files defined. Will add current file to agenda files.")
endif
call s:CurfileAgenda()
endif
if exists('b:v.sparse_list') && (len(b:v.sparse_list) > 0)
call s:ClearSparseTree()
endif
call s:MakeResults(a:search_spec,sparse_search)
if sparse_search
call s:ResultsToSparseTree()
else
call s:ResultsToAgenda( search_type )
endif
finally
"set mouseshape-=n:busy,v:busy,i:busy
endtry
endfunction
function! s:ResultsToAgenda( search_type )
" FOR OrgRunSearch()
":AAgenda
:EditAgenda
let b:v={}
call s:AgendaBufSyntax()
set nowrap
call s:DoAgendaMaps()
let i = 0
call s:ADictPlaceSigns()
let b:v.heading_marks_dict = {}
"call setline(line('$'), ["Headlines matching search spec: ".g:org_search_spec,''])
let lines = []
let lines = lines + ["Headlines matching search spec: ".g:org_search_spec,'']
if a:search_type ==? 'agenda_todo'
let msg = "Press <num>r to re-search: "
let numstr= ''
nmap <buffer> r :call OrgRunSearch(g:org_search_spec,'agenda_todo')<cr>
let tlist = ['ANY_TODO','UNFINISHED_TODOS', 'FINISHED_TODOS'] + s:Union(g:org_todoitems,[])
for item in tlist
let num = index(tlist,item)
let numstr .= '('.num.')'.item.' '
execute "nmap <buffer> ".num."r :silent call OrgRunCustom({'redo_num':line('.'), 'type':'tags-todo', 'spec':'". tlist[num] . "'})<CR>"
endfor
"call add(lines,split(msg.numstr,'\%72c\S*\zs '))
let lines = lines + split(msg.numstr,'\%72c\S*\zs ')
call add(lines,'')
endif
for key in sort(keys(g:adict))
call add(lines , key . ' ' .
\ printf("%-12.12s",g:adict[key].CATEGORY ) . ' ' .
\ s:PrePad(matchstr(g:adict[key].ITEM,'^\*\+ '),8) .
\ matchstr(g:adict[key].ITEM,'\* \zs.*$'))
let i += 1
endfor
call append(s:agenda_insert_point,lines)
endfunction
function! s:ToFromAgenda()
if bufname('%') == '__Agenda__'
for i in range(1, winnr('$'))
exe i . 'wincmd w'
if bufname('%') !~ '__Agenda__\|__Calendar'
break
endif
endfor
"windo if bufname('%') !~ '__Agenda__\|__Calendar' | let return | endif
elseif bufwinnr('__Agenda__') > 0
exec bufwinnr('__Agenda__') . 'wincmd w'
endif
endfunction
function! s:DoAgendaMaps()
execute "source " . s:sfile . '/vimorg-agenda-mappings.vim'
command! -buffer -nargs=* Agenda :call OrgAgendaCommand(<f-args>)
" user can have a function in their vimrc to have their own
" agenda mappings
if exists('*OrgCustomAgendaMaps')
call OrgCustomAgendaMaps()
endif
endfunction
function! s:OrgAgendaTab()
if getline(line(".")) !~ '^\d\+'
return
endif
let thisline = getline(line('.'))
let file = s:agenda_files_copy[str2nr(matchstr(thisline, '^\d\d\d'))]
if bufwinnr(file) == -1
call s:OrgAgendaToBuf()
else
call s:MoveToHeadingFromAgenda(line('.'))
if b:v.chosen_agenda_heading != line('.')
"back to agenda and do agendatobuf from there
call org#LocateFile('__Agenda__')
call s:OrgAgendaToBuf()
else
" we're in file buffer, ready to cycle
call s:OrgCycle(line('.'))
call org#LocateFile('__Agenda__')
endif
endif
endfunction
function! s:ToggleHeadingMark(line)
let line = a:line
if (bufname('%') == '__Agenda__' && getline(line) !~ '^\d\{8}\s')
\ || ((&filetype == 'org') && getline(line) !~ b:v.headMatch)
return
endif
let list_item = get(b:v.heading_marks_dict, line)
if list_item == 0
let b:v.heading_marks_dict[line] = 1
execute "sign place " . line('.') . " line=" . line('.') . " name=marked buffer=".bufnr("%")
else
unlet b:v.heading_marks_dict[line]
execute "sign unplace " . line('.') . " buffer=".bufnr("%")
endif
endfunction
function! s:DeleteHeadingMarks()
if bufname('%')=='__Agenda__'
for item in keys(b:v.heading_marks_dict)
execute "sign unplace " . item . " buffer=".bufnr("%")
endfor
else
sign unplace *
endif
let b:v.heading_marks = []
let b:v.heading_marks_dict = {}
endfunction
function! s:ResultsToSparseTree()
"call s:ClearSparseTree()
let w:sparse_on = 1
let temp = []
for key in keys(g:adict)
call add(temp,g:adict[key].LINE)
endfor
let b:v.sparse_list = sort(temp,'s:NumCompare')
"for key in keys(g:adict)
" call add(b:v.sparse_heads,str2nr(key))
"endfor
"for item in sort(b:v.sparse_heads,'NumCompare')
call sort(b:v.fold_list,"s:NumCompare")
call s:SparseTreeDoFolds()
"for item in sort(b:v.fold_list,'NumCompare')
set fdm=expr
set foldlevel=0
call clearmatches()
for item in b:v.sparse_list
if item > 11
execute item - g:org_sparse_lines_after
normal! zv
call matchadd('Search','\%' . (item - g:org_sparse_lines_after) . 'l')
endif
endfor
execute 1
endfunction
function! s:TestTime()
let g:timestart=join(reltime(), ' ')
let g:start = strftime("%")
let i = 0
set fdm=expr
let g:timefinish=join(reltime(), ' ')
echo g:timestart . ' --- ' . g:timefinish
endfunction
function! s:TestTime2(fu)
let g:timestart=join(reltime(), ' ')
let g:start = strftime("%")
let i = 0
execute a:fu
let g:timefinish=join(reltime(), ' ')
echo g:timestart . ' --- ' . g:timefinish
endfunction
function! s:ADictPlaceSigns()
let myl=[]
call s:DeleteSigns() " signs were placed during search
for key in keys(g:adict)
let headline = matchstr(key,'^\d\d\d\zs\d\+')
let filenum = str2nr(key[0:2])
let buf = bufnr(s:agenda_files_copy[filenum])
try
silent execute "sign place " . headline . " line="
\ . headline . " name=piet buffer=" . buf
catch
echo "ERROR: headline " . headline . ' and buf ' .buf
echo key .', '. matchstr(key,'^.*\ze_\d\+$')
finally
endtry
endfor
endfunction
function! s:DateDictPlaceSigns()
let myl=[]
call s:DeleteSigns() " signs were placed in GetDateHeads
for key in keys(g:agenda_date_dict)
let myl = get(g:agenda_date_dict[key], 'l')
if len(myl) > 0
for item in myl
let dateline = matchstr(item,'^\d\d\d\zs\d\+')
let filenum = str2nr(item[0:2])
let buf = bufnr(s:agenda_files_copy[filenum])
try
silent execute "sign place " . dateline . " line="
\ . dateline . " name=piet buffer=" . buf
catch
echo "ERROR: headline " . headline . ' and buf ' . buf . ' and dateline ' . dateline
echo (matchstr(item,'^\d\+\s\+\zs\S\+') . '.org')
finally
endtry
endfor
endif
endfor
endfunction
function! s:DateDictToScreen()
":%d "delete all lines
let lines = ["Press <f> or <b> for next or previous period, q to close agenda," ,
\ "<Enter> on a heading to synch main file, <ctl-Enter> to goto line," ,
\ "<tab> to cycle heading text, <shift-Enter> to cycle Todos.",'']
let search_spec = g:org_search_spec ># '' ? g:org_search_spec : 'None - include all heads'
let d = g:org_agenda_days
let start_week = 'W' . org#ISODateToYWD(g:agenda_startdate)[1]
let end_date = calutil#cal(calutil#jul(g:agenda_startdate)+g:org_agenda_days-1)
let end_week = 'W' . org#ISODateToYWD(end_date)[1]
if d==1 | let type = 'Day-agenda (' . start_week . '):'
elseif d==7 | let type = 'Week-agenda (' . start_week . '):'
elseif (d>27 && d<32) | let type = 'Month-agenda (' . start_week . '-' . end_week . '):'
elseif (d>364 && d<366) | let type = 'Year-agenda:'
else | let type = 'Agenda:'
endif
call add(lines,"Agenda view for " . g:agenda_startdate
\ . " to ". calutil#cal(calutil#jul(g:agenda_startdate)+g:org_agenda_days-1)
\ . ' matching FILTER: ' . search_spec )
call add(lines,'')
call add(lines,type)
call s:DateDictPlaceSigns()
let b:v.heading_marks_dict = {}
let gap = 0
let mycount = len(keys(g:agenda_date_dict))
for key in sort(keys(g:agenda_date_dict))
if empty(g:agenda_date_dict[key].l)
let gap +=1
call add(lines, g:agenda_date_dict[key].marker)
else
if (gap > g:org_agenda_skip_gap) && (g:org_agenda_minforskip <= mycount)
call remove(lines, len(lines)-gap, -1 )
let lines = lines + ['',' [. . . ' .gap. ' empty days omitted ]','']
endif
let gap = 0
call add(lines, g:agenda_date_dict[key].marker)
if ((g:org_agenda_days == 1) || (key == strftime("%Y-%m-%d"))) && exists('g:org_timegrid') && (g:org_timegrid != [])
let lines = lines + s:PlaceTimeGrid(g:agenda_date_dict[key].l)
else
let lines = lines + g:agenda_date_dict[key].l
endif
endif
endfor
if (gap > g:org_agenda_skip_gap) && (g:org_agenda_minforskip <= mycount)
call remove(lines, len(lines)-gap, -1 )
let lines = lines + ['',' [. . . ' .gap. ' empty days omitted ]','']
endif
" finally, place all the prepared result lines in agenda buffer
call append(s:agenda_insert_point-1, lines)
endfunction
function! s:TimeGridSort(s1, s2)
return (a:s1[23:] == a:s2[23:]) ? 0 : (a:s1[23:] > a:s2[23:]) ? 1 : -1
endfunction
function! s:PlaceTimeGrid(lines)
let lines = a:lines
" assemble timegrid for agenda view
if lines[0] =~ '\%24c\d\d:\d\d'
"if, at least one time item put grid lines in and sort with other time items
let grid = s:TimeGrid(g:org_timegrid[0],g:org_timegrid[1],g:org_timegrid[2])
let lines = grid + lines
let i = len(grid) - 1
while (matchstr(lines[i],'\%24c\d\d:\d\d') && i < len(lines))
let i += 1
endwhile
let lines = sort(lines[0:i-1], 's:TimeGridSort') + lines[i :]
" now delete duplicates where grid is same as actual entry
" skip this part until rest is working. . .
"let i = 0
"while i < len(lines)
" let match1 = matchstr(getline(line('.')),'\%24c.*\%29c')
" let match2 = matchstr(getline(line('.')-1),'\%24c.*\%29c')
" if match1 ==? match2
" if match1[0] ==? ' '
" normal ddk
" else
" normal kdd
" endif
" endif
" exec line('.')-1
"endwhile
endif
return lines
endfunction
function! OrgRunAgenda(date,count,...)
try
if bufname('%') ==? '__Agenda__'
"wincmd k
endif
let g:agenda_head_lookup={}
let win = bufwinnr('Calendar')
let file = expand('%:p')
if win >= 0
execute win . 'wincmd w'
normal ggjjj
wincmd l
execute 'bw!' . bufnr('Calendar')
endif
if !exists("g:agenda_files") || (g:agenda_files == [])
unsilent call confirm("No agenda files defined. Will add current file to agenda files.")
call s:CurfileAgenda()
endif
if exists('b:v.sparse_list') && (len(b:v.sparse_list) > 0)
call s:ClearSparseTree()
endif
" a:1 is search_spec, a:2 is "today" for search
if a:0 == 1
call s:MakeAgenda(a:date,a:count,a:1)
elseif a:0 == 2
call s:MakeAgenda(a:date,a:count,a:1,a:2)
else
call s:MakeAgenda(a:date,a:count)
endif
AAgenda
call s:SetupDateAgendaWin()
"we are no in newly created agenda buf/window
for key in keys(g:agenda_date_dict)
call sort(g:agenda_date_dict[key].l, 's:AgendaCompare')
endfor
call s:DateDictToScreen()
if win >= 0
let year = matchstr(t:agenda_date,'\d\d\d\d')
let month = matchstr(t:agenda_date,'\d-\zs\d\d\ze-')
execute 'Calendar ' . year .' '. str2nr(month)
execute bufwinnr('Agenda').'wincmd w'
endif
" we're in agenda, do rigamarole to get top column heading window,
" if any, back to zero height
let curheight=winheight(0)
call org#LocateFile(file)
"wincmd k
resize
call org#LocateFile('__Agenda__')
"wincmd j
execute 1
execute 'resize ' . curheight
finally
"set mouseshape-=n:busy,v:busy,i:busy
endtry
endfunction
function! OrgRunCustom(arg)
call s:RunCustom(a:arg)
endfunction
function! s:SetupDateAgendaWin()
EditAgenda
let b:v={}
call s:AgendaBufSyntax()
set nowrap
call s:DoAgendaMaps()
command! -buffer -nargs=* Agenda :call OrgAgendaCommand(<f-args>)
endfunction
function! OrgRefreshCalendarAgenda()
let g:org_search_spec = matchstr(getline(5),'FILTER:\s*\zs.*$')
if g:org_search_spec =~ '\c^None'
let g:org_search_spec = ''
endif
call OrgRunCustom({'redo_num': line('.'),'type':'agenda', 'agenda_date': g:agenda_startdate, 'agenda_duration': g:org_agenda_days, 'spec': g:org_search_spec})
endfunction
function! s:Resize()
let cur = winheight(0)
resize
resize cur
endfunction
function! s:GetDateHeads(date1,count,...)
" a:1 is date for warnings
let save_cursor=getpos(".")
if g:org_search_spec ># ''
let b:v.agenda_ifexpr = s:OrgIfExpr()
endif
let g:date1 = a:date1
let date1 = a:date1
let date2 = calutil#Jul2Cal(calutil#Cal2Jul(split(date1,'-')[0],split(date1,'-')[1],split(date1,'-')[2]) + a:count)
execute 1
while search('[^-][[<]\d\d\d\d-\d\d-\d\d','W') > 0
"if ((g:org_search_spec ># '') && (s:CheckIfExpr(line("."),b:v.agenda_ifexpr)==0))
" continue
"endif
let repeatlist = []
let line = getline(line("."))
let datematch = matchstr(line,'[[<]\d\d\d\d-\d\d-\d\d\ze')
let repeatmatch = matchstr(line, '<\d\d\d\d-\d\d-\d\d.*[ +.]+\d\+\S\+.*>\ze')
if repeatmatch != ''
" if date has repeater then call once for each repeat in period
let repeatlist = s:RepeatMatch(repeatmatch[1:],date1,date2)
for dateitem in repeatlist
if a:0 == 1
call s:ProcessDateMatch(dateitem,date1,date2,a:1)
else
call s:ProcessDateMatch(dateitem,date1,date2)
endif
endfor
else
if (datematch[0]!='[') || g:org_clocks_in_agenda
if a:0 == 1
call s:ProcessDateMatch(datematch[1:],date1,date2,a:1)
else
call s:ProcessDateMatch(datematch[1:],date1,date2)
endif
endif
endif
"endif
endwhile
call setpos(".",save_cursor)
endfunction
function! s:ProcessDateMatch(datematch,date1,date2,...)
if a:0 > 0
let today = a:1
else
let today = strftime("%Y-%m-%d")
endif
let datematch = a:datematch
let rangedate = matchstr(getline(line(".")),'--<\zs\d\d\d\d-\d\d-\d\d')
let locator = s:PrePad(s:filenum,3,'0') . s:PrePad(line('.'),5,'0') . ' '
let g:myline = s:OrgGetHead_l(line('.'))
"let g:myline = s:OrgParentHead_l(line('.'))
"if g:myline == 0
" let filename = org#Pad(b:v.org_dict[g:myline].CATEGORY,13)
"else
"let filename = org#Pad(b:v.org_dict.iprop(g:myline,'CATEGORY'),12) . ' '
let filename = printf("%-12.12s",b:v.org_dict.iprop(g:myline,'CATEGORY')) . ' '
"endif
let line = getline(line("."))
let date1 = a:date1
let date2 = a:date2
let s:headline=0
if (datematch >= date1) && (datematch < date2)
\ && ((g:org_search_spec ==# '') || (s:CheckIfExpr(line("."),b:v.agenda_ifexpr)))
let mlist = matchlist(line,'\(DEADLINE\|SCHEDULED\|CLOSED\)')
call s:SetHeadInfo()
if empty(mlist)
" it's a regular date, first check for time parts
let tmatch = matchstr(line,' \zs\d\d:\d\d\ze.*[[>]')
if tmatch ># ''
let tmatch2 = matchstr(line,'<.\{-}-\zs\d\d:\d\d\ze.*>')
if tmatch2 ># ''
let tmatch .= '-' . tmatch2
else
if match(line,':\s*CLOCK\s*:') >= 0
let tmatch .= '-'.matchstr(line,'--\[.\{-}\zs\d\d:\d\d\ze\]')
let s:headtext = s:headtext[0:6] . 'Clocked: ('.matchstr(line,'->\s*\zs.*$') .') '.s:headtext[7:]
else
let tmatch .= '......'
endif
endif
endif
call add(g:agenda_date_dict[datematch].l, locator . filename . org#Pad(tmatch,11) . s:headtext)
"call add(g:agenda_date_dict[datematch].l, line(".") . repeat(' ',6-len(line("."))) . filename . org#Pad(tmatch,11) . s:headtext)
if rangedate != ''
"let startdate = matchstr(line,'<\zs\d\d\d\d-\d\d-\d\d\ze')
"let thisday = calutil#jul(datematch) - calutil#jul(startdate) + 1
let days_in_range = calutil#jul(rangedate) - calutil#jul(datematch) + 1
"let rangestr = '('.thisday.'/'.days_in_range.')'
let i = days_in_range
"while (rangedate < date2) && (rangedate > datematch)
while (rangedate > datematch)
let rangestr = '('.i.'/'.days_in_range.')'
if exists("g:agenda_date_dict['".rangedate."']")
"call add(g:agenda_date_dict[rangedate].l, line(".") . repeat(' ',6-len(line("."))) .
call add(g:agenda_date_dict[rangedate].l, locator .
\ filename . org#Pad(rangestr,11) . s:headtext)
endif
let rangedate = calutil#cal(calutil#jul(rangedate) - 1)
let i = i - 1
endwhile
" to end of line to avoid double
" treatment
normal $
endif
else
" it's a deadline/scheduled/closed date
let type = org#Pad(mlist[1][0] . tolower(mlist[1][1:]) . ':' , 11)
call add(g:agenda_date_dict[datematch].l, locator . filename . type . s:headtext)
endif
endif
" Now test for late and upcoming warnings if 'today' is in range and not
" a done-type todo
if (today >= date1) && (today < date2) && (getline(g:myline) !~ b:v.todoDoneMatch)
if (datematch < today) && (match(line,'\(DEADLINE\|SCHEDULED\)')>-1)
\ && ((g:org_search_spec ==# '') || (s:CheckIfExpr(line("."),b:v.agenda_ifexpr)))
let mlist = matchlist(line,'\(DEADLINE\|SCHEDULED\)')
call s:SetHeadInfo()
if !empty(mlist)
let dayspast = calutil#jul(today) - calutil#jul(datematch)
if mlist[1] ==? 'DEADLINE'
let newpart = org#Pad('In',6-len(dayspast)) . '-' . dayspast . ' d.:'
else
let newpart = org#Pad('Sched:',9-len(dayspast)) . dayspast . 'X:'
endif
call add(g:agenda_date_dict[today].l, locator . filename . newpart . s:headtext)
endif
" also put in warning entry for deadlines when appropriate
elseif (datematch > today) && (match(line,'DEADLINE')>-1)
\ && ((g:org_search_spec ==# '') || (s:CheckIfExpr(line("."),b:v.agenda_ifexpr)))
let mlist = matchlist(line,'DEADLINE')
call s:SetHeadInfo()
if !empty(mlist)
let daysahead = calutil#jul(datematch) - calutil#jul(today)
let g:specific_warning = str2nr(matchstr(line,'<\S*\d\d.*-\zs\d\+\zed.*>'))
if (daysahead <= g:org_deadline_warning_days) || (daysahead <= g:specific_warning)
let newpart = org#Pad('In',7-len(daysahead)) . daysahead . ' d.:'
call add(g:agenda_date_dict[today].l, locator . filename . newpart . s:headtext)
endif
endif
endif
endif
" finally handle things for a range that began before date1
if (rangedate != '') && (datematch < date1)
\ && ((g:org_search_spec ==# '') || (s:CheckIfExpr(line("."),b:v.agenda_ifexpr)))
let days_in_range = calutil#jul(rangedate) - calutil#jul(datematch) + 1
if rangedate >= date2
let last_day_to_add = calutil#jul(date2) - calutil#jul(datematch)
let rangedate = calutil#cal(calutil#jul(date2)-1)
else
let last_day_to_add = days_in_range
endif
call s:SetHeadInfo()
let i = last_day_to_add
while (rangedate >= date1)
let rangestr = '('.i.'/'.days_in_range.')'
call add(g:agenda_date_dict[rangedate].l, locator .
\ filename . org#Pad(rangestr,11) . s:headtext)
let rangedate = calutil#cal(calutil#jul(rangedate) - 1)
let i = i - 1
endwhile
" go past match to avoid double treatment
normal $
endif
if s:headline > 0
let g:agenda_head_lookup[line(".")]=s:headline
endif
endfunction
function! s:SetHeadInfo()
let s:headline = s:OrgGetHead_l(line("."))
let s:headtext = getline(s:headline)
let s:mystars = matchstr(s:headtext,'^\*\+')
let s:headstars = s:PrePad(s:mystars,6)
let s:headtext = s:headstars . ' ' . s:headtext[len(s:mystars)+1:]
endfunction
function! s:RepeatMatch(rptdate, date1, date2)
let yearflag = 0
let basedate = matchstr(a:rptdate,'\d\d\d\d-\d\d-\d\d')
if basedate >= a:date2
" no need for repeat, rturn to check fo deadlien warnings
return [basedate]
endif
let date1 = a:date1
if basedate > date1
let date1 = basedate
endif
let baserpt = matchstr(a:rptdate, ' \S\S\S [.+]\{0,1}+\zs\S\+\ze.*>')
let rptnum = matchstr(baserpt, '^\d\+')
let rpttype = matchstr(baserpt, '^\d\+\zs.')
let g:rptlist = []
let date1jul = calutil#jul(date1)
let date2jul = calutil#jul(a:date2)
if rpttype ==? 'w'
let rpttype = 'd'
let rptnum = str2nr(rptnum)*7
endif
if rpttype ==? 'y'
let rpttype = 'm'
let rptnum = str2nr(rptnum)*12
let yearflag = 1
endif
if rpttype ==? 'd'
let dmod = (date1jul - calutil#jul(basedate)) % rptnum
let i = 0
while 1
let testjul = date1jul - dmod + (i*rptnum)
if testjul < date2jul
call add(g:rptlist, calutil#cal(testjul))
else
break
endif
let i += 1
endwhile
elseif rpttype ==? 'm'
let g:special = baserpt[-1:]
let monthday = str2nr(basedate[8:])
let baseclone = basedate
" this if-structure assigns begin test month as
" first repeat month _before_ date1
if yearflag
if (date1[:6]) >= (date1[:3] . baseclone[4:6])
let baseclone = date1[:3] . baseclone[4:]
else
let baseclone = string(str2nr(date1[:3]) - 1) . baseclone[4:]
endif
let first_of_month_jul = calutil#jul(baseclone[:7]. '01')
else
let first_of_month_jul = calutil#jul(date1[:4] .
\ s:Pre0( date1[5:6] - 1) . '-01')
endif
if g:special ==? '*'
let specialnum = (monthday / 7) + 1
let specialdaynum = calutil#dow(basedate)
endif
while 1
if g:special != '*'
let testjul = first_of_month_jul - 1 + monthday
else
" process for 'xth weekday of month' type
let fdow = calutil#dow(calutil#cal(first_of_month_jul))
if fdow == specialdaynum
let testjul = first_of_month_jul + (specialnum-1)*7
elseif fdow < specialdaynum
let testjul = first_of_month_jul + (specialnum-1)*7
\ + (specialdaynum - fdow)
elseif fdow > specialdaynum
let testjul = first_of_month_jul + (specialnum*7)
\ - (fdow - specialdaynum)
endif
endif
if (testjul < date2jul) && (testjul >= first_of_month_jul)
call add(g:rptlist, calutil#cal(testjul))
else
"put in this one to check for deadlien warnings
"if len(g:rptlist)>0
call add(g:rptlist, calutil#cal(testjul))
"endif
break
endif
let first_cal = calutil#cal(first_of_month_jul)
let nextmonth = str2nr(first_cal[5:6]) + rptnum
let year = str2nr(first_cal[0:3])
if nextmonth >= 13
let nextmonth = (nextmonth-12)
let year += 1
endif
let first_of_month_jul = calutil#jul(string(year) . '-' . s:Pre0(nextmonth) . '-01')
endwhile
endif
return g:rptlist
endfunction
function! s:BufMinMaxDate()
let b:v.MinMaxDate=['2099-12-31','1900-01-01']
g/<\d\d\d\d-\d\d-\d\d/call s:CheckMinMax()
endfunction
function! s:CheckMinMax()
let date = matchstr(getline(line(".")),'<\zs\d\d\d\d-\d\d-\d\d')
if (date < b:v.MinMaxDate[0])
let b:v.MinMaxDate[0] = date
endif
if (date > b:v.MinMaxDate[1])
let b:v.MinMaxDate[1] = date
endif
endfunction
function! s:Timeline(...)
if a:0 > 0
let spec = a:1
else
let spec = ''
endif
if bufname("%") ==? '__Agenda__'
"go back up to main org buffer
"wincmd k
endif
if exists('g:org_search_spec')
let prev_spec = g:org_search_spec
endif
if exists('g:agenda_files')
let prev_files = g:agenda_files
endif
exec "let g:agenda_files=['".substitute(expand("%:p"),' ','\\ ','g')."']"
call s:BufMinMaxDate()
let num_days = 1 + calutil#jul(b:v.MinMaxDate[1]) - calutil#jul(b:v.MinMaxDate[0])
try
"AAgenda
call OrgRunAgenda(b:v.MinMaxDate[0], num_days,spec)
finally
if exists('prev_spec')
let g:org_search_spec = prev_spec
endif
if exists('prev_files')
let g:agenda_files = prev_files
endif
endtry
endfunction
function! s:Pre0(s)
return repeat('0',2 - len(a:s)) . a:s
endfunction
function! s:PrePad(s,amt,...)
if a:0 > 0
let char = a:1
else
let char = ' '
endif
return repeat(char,a:amt - len(a:s)) . a:s
endfunction
function! s:AgendaCompare(i0, i1)
let mymstr = '^\(\d\+\)\s\+\(\S\+\)\s\+\(\%24c.\{11}\).*\(\*\+\)\s\(.*$\)'
" mymstr below would be better match string regex, but generic dates
" have no text at position 24 to match \S . . . "
"let mymstr = '^\(\d\+\)\s\+\(\S\+\)\s\+\(\S.\{10}\).*\(\*\+\)\s\(.*$\)'
" [1] is lineno, [2] is file, [3] is scheduling, [4] is levelstarts,
" [5] is headtext
let cp0 = matchlist(a:i0,mymstr)
let cp1 = matchlist(a:i1,mymstr)
let myitems = [cp0, cp1]
let sched_comp = []
let i = 0
while i < 2
let item = myitems[i]
if item[3][0] ==? 'S'
if item[3][5] ==? ':'
"let str_ord = 'a' . substitute(item[3][6:8],' ', '0','')
let str_ord = 'aa' . s:PrePad(1000-str2nr(item[3][6:8]),' ', '0')
else
let str_ord = 'ab000'
endif
elseif item[3][0] ==? 'I'
if matchstr(item[3],'-') ># ''
let str_ord = 'd-'.s:PrePad(1000-str2nr(matchstr(item[3],'\d\+')),3,'0')
else
let str_ord = 'da'.s:PrePad(matchstr(item[3],'\d\+'),3,'0')
endif
elseif item[3][0] ==? 'D'
let str_ord = 'd0000'
elseif item[3][0] ==? ' '
let str_ord = 'zzzzz'
else
let str_ord = item[3][:4]
endif
call add(sched_comp,str_ord.item[2].s:PrePad(item[1],5,'0'))
let i += 1
endwhile
return sched_comp[0] ==? sched_comp[1] ? 0 : sched_comp[0] > sched_comp[1] ? 1 : -1
" let num1 = str2nr(matchstr(a:i1,'In *\zs[ -]\d\+\ze d.:'))
" let num2 = str2nr(matchstr(a:i2,'In *\zs[ -]\d\+\ze d.:'))
" if num1 == 0
" let num1 = str2nr(matchstr(a:i1,'Sched: *\zs\d\+\zeX:'))
" if num1 !=0
" let num1 = -num1 - 10000
" endif
" endif
" if num2 == 0
" let num2 = str2nr(matchstr(a:i2,'Sched: *\zs\d\+\zeX:'))
" if num2 !=0
" let num2 = -num2 - 10000
" endif
" endif
" if (a:i1 =~ '^\d\+\s\+\S\+\s\+\d')
" let num1=num1-20000
" endif
" if (a:i2 =~ '^\d\+\s\+\S\+\s\+\d')
" let num2=num2-20000
" endif
" return num1 == num2 ? 0 : num1 > num2 ? 1 : -1
endfunc
function! s:DateListAdd(valdict)
let namelist = [' GENERAL','SCHEDULED','CLOSED','DEADLINE']
let templist = []
call add(templist, get(a:valdict,'ud',0))
call add(templist, get(a:valdict,'sd',0))
call add(templist, get(a:valdict,'cd',0))
call add(templist, get(a:valdict,'dd',0))
let i = 0
while i < 4
if templist[i] != 0
call add(g:org_datelist, templist[i] . ' ' . namelist[i] . ' ' . a:valdict.l )
endif
let i += 1
endwhile
return a:valdict
endfunction
function! OrgAgendaMove(direction,count)
" need to add functionaity for count, refactor
let cnt = (a:count == 0) ? 1 : a:count
let cnt = (a:direction ==? 'forward') ? cnt : -cnt
let date_jul = calutil#jul(g:agenda_startdate)
let ymd_list = split(g:agenda_startdate,'-')
if g:org_agenda_days == 1
let g:agenda_startdate = calutil#cal(date_jul + (cnt * 1))
elseif g:org_agenda_days == 7
let g:agenda_startdate = calutil#cal(date_jul + (cnt * 7))
elseif g:org_agenda_days >= 360
let g:agenda_startdate = string(ymd_list[0] + (cnt * 1)) .'-01-01'
else
let ymd_list[1] = ymd_list[1] + (cnt * 1)
if ymd_list[1] > 0
let ymd_list[0] += ymd_list[1] / 12
let ymd_list[1] = ymd_list[1] % 12
else
let ymd_list[0] += (ymd_list[1] / 12) - 1
let ymd_list[1] = 12 + (ymd_list[1] % 12)
endif
let g:agenda_startdate = ymd_list[0] . '-' .
\ s:Pre0(string(ymd_list[1])) .'-01'
let g:org_agenda_days = s:DaysInMonth(g:agenda_startdate)
endif
if g:org_agenda_days == 1
"call OrgRunAgenda(g:agenda_startdate,g:org_agenda_days,g:org_search_spec,g:agenda_startdate)
call OrgRunCustom({'redo_num': line('.'), 'type':'agenda', 'agenda_date': g:agenda_startdate, 'agenda_duration': g:org_agenda_days, 'spec': g:org_search_spec})
else
"call OrgRunAgenda(g:agenda_startdate,g:org_agenda_days,g:org_search_spec)
call s:RunCustom({'redo_num': line('.'), 'type':'agenda', 'agenda_date': g:agenda_startdate, 'agenda_duration': g:org_agenda_days ,'spec': g:org_search_spec})
endif
endfunction
function! s:TimeGrid(starthour,endhour,inc)
let result = []
for i in range(a:starthour, a:endhour,a:inc)
call add(result,repeat(' ',23).s:Pre0(i).':00...... ------------')
endfor
return result
endfunction
function! s:MakeCalendar(date, daycount)
"function! s:MakeCalendar(year, month, day, daycount)
" this function is taken from vim tip by Siegfried Bublitz
" at: http://vim.wikia.com/wiki/Generate_calendar_file
" with many mods to 1.output to list rather than to buffer
" and 2. get weekday and weekno from calutils
let g:agenda_date_dict = {}
let g:agenda_head_lookup = {}
"let startdate = calutil#Jul2Cal((calutil#Cal2Jul(a:year,a:month,a:day) - calutil#DayOfWeek(a:year,a:month,a:day)))
let year = split(a:date,'-')[0]
let month = split(a:date,'-')[1]
let day = split(a:date,'-')[2]
let day = str2nr(day)
if a:daycount == 7
let wd = 1
elseif (a:daycount>=28) && (a:daycount <=31)
let wd = calutil#dow(a:date[0:7].'01') + 1
else
let wd = calutil#dow(a:date) + 1
endif
let week = 1 + (calutil#Cal2Jul(year,month,day) - calutil#Cal2Jul(year,1,1)) / 7
let index = 0
let datetext = ''
let diy = 777 " day in year, wrong before next year
while (index < a:daycount) " no of days to output
let diy = diy + 1
if (wd > 7)
let wd = 1
let week = week + 1
if (week >= 53)
if (week >= 54)
let week = 1
elseif (day >= 28 || day <= 3)
let week = 1
endif
endif
endif
let monthnames=['January','February','March','April','May','June','July',
\ 'August','September','October','November','December']
"let daynames = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
let daynames = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
let dn = daynames[wd-1]
if ((day > 31) || (month == 2 && (day > 29 || day > 28 && year % 4))
\ || (month == 4 && day > 30) || (month == 6 && day > 30)
\ || (month == 9 && day > 30) || (month == 11 && day > 30))
let day = 1
let month = month + 1
if (month > 12)
let month = 1
let diy = 1
let year = year + 1
if (wd <= 3)
let week = 1
endif
endif
endif
let datetext = dn . repeat(' ',10-len(dn)) . (day<10?' ':' ') .
\ day . ' ' . monthnames[month-1] . ' ' . year . (wd == 1 ? ' Wk' . week : '' )
let g:agenda_date_dict[year . '-' . s:Pre0(month) . '-' . (day<10 ? '0'.day : day) ]
\ = {'marker': datetext, 'l': [] }
let index = index + 1
let day = day + 1
let wd = wd + 1
endwhile
endfunction
function! s:ActualBufferLine(lineref_in_agenda,bufnumber)
let actual_line = matchstr(s:GetPlacedSignsString(a:bufnumber),'line=\zs\d\+\ze\s\+id='.a:lineref_in_agenda)
return actual_line
endfunction
function! s:AgendaPutText(...)
let save_cursor = getpos(".")
let thisline = getline(line("."))
if thisline =~ '^\d\+\s\+'
if (getline(line(".") + 1) =~ '^\*\+ ')
"let file = matchstr(thisline,'^\d\+\s\+\zs\S\+\ze')
"let file = s:filedict[str2nr(matchstr(thisline, '^\d\d\d'))]
let file = s:agenda_files_copy[str2nr(matchstr(thisline, '^\d\d\d'))]
"let lineno = matchstr(thisline,'^\d\+\ze\s\+')
let lineno = str2nr(matchstr(thisline,'^\d\d\d\zs\d*'))
let starttab = tabpagenr()
"call org#LocateFile(file.'.org')
call org#LocateFile(file)
if g:agenda_date_dict != {}
"let confirmhead = g:agenda_head_lookup[lineno]
let confirmhead = lineno
elseif g:adict != {}
let confirmhead = lineno
endif
let newhead = matchstr(s:GetPlacedSignsString(bufnr("%")),'line=\zs\d\+\ze\s\+id='.confirmhead)
let newhead = s:OrgGetHead_l(newhead)
execute newhead
let lastline = s:OrgNextHead_l(newhead) - 1
if lastline > newhead
let g:text = getline(newhead,lastline)
elseif lastline == -1
let g:text = getline(newhead,line('$'))
else
let g:text = []
endif
execute 'tabnext ' . starttab
execute bufwinnr('Agenda').'wincmd w'
call setpos(".",save_cursor)
" okay, we're back in agenda and have main buffer's
" text in g:text, now need to compare it
normal j
let firstline = line(".")
let daytextpat = '^\S\+\s\+\d\{1,2}\s\S\+\s\d\d\d\d'
while (getline(line(".")) !~ '^\d\+\s\+') && (line(".") != line("$"))
\ && (getline(line(".")) !~ daytextpat)
\ && (getline(line(".")) !~ '\d empty days omitted')
normal j
endwhile
let lastline = line(".")
if (lastline < line("$")) ||
\ ( (getline(line(".")) =~ '^\d\+\s\+')
\ || (getline(line(".")) =~ daytextpat)
\ || (getline(line(".")) =~ '\d empty days omitted') )
let lastline = line(".") - 1
endif
"execute firstline . ', ' . lastline . 'd'
if g:text ==? getline(firstline, lastline)
echo "headings are identical"
else
if g:adict != {}
let resp = confirm("Heading's text has changed, save changes?","&Save\n&Cancel",1)
if resp == 1
call s:SaveHeadline(file, newhead,getline(firstline,lastline))
"call s:SaveHeadline(file, confirmhead,getline(firstline,lastline))
else
echo "Changes were _not_ saved."
endif
else
call confirm("Heading's text has changed, but saving is\n"
\ . "temporarily disabled for date-based agenda views.\n"
\ . "No changes are being saved, original buffer text remains as it was.")
endif
endif
endif
else
echo "You're not on a headline line."
endif
call setpos(".",save_cursor)
endfunction
function! s:SaveHeadline(file, headline, lines)
let file = a:file
let headline = a:headline
let lines=a:lines
let starttab = tabpagenr()
"call org#LocateFile(file.'.org')
call org#LocateFile(file)
"let newhead = matchstr(s:GetPlacedSignsString(bufnr("%")),'line=\zs\d\+\ze\s\+id='.headline)
let newhead = a:headline
execute newhead
let lastline = s:OrgNextHead_l(newhead) - 1
execute newhead+1.','.lastline.'d'
" don't delete orig headline b/c that's where sign is placed
call setline(newhead,lines[0])
call append(newhead,lines[1:])
execute 'tabnext ' . starttab
execute bufwinnr('Agenda').'wincmd w'
endfunction
function! OrgAgendaGetText(...)
"type: 'datedict' for date agenda, 'adict' for regular search
let cycle_todo = 0
if a:0 >= 1
let cycle_todo = 1
if a:0 == 2
let newtodo = a:2
endif
endif
" called by <TAB> map to toggle view of heading's body text in agenda
" view
let save_cursor = getpos(".")
let thisline = getline(line("."))
let curTodo = matchstr(thisline, '\*\+ \zs\S\+')
if thisline =~ '^\d\+\s\+'
if (getline(line(".") + 1) =~ '^\d\+\s\+') || (line(".") == line("$")) ||
\ (getline(line(".") + 1 ) =~ '^\S\+\s\+\d\{1,2}\s\S\+\s\d\d\d\d')
\ || (getline(line(".") + 1 ) =~ '\d empty days omitted')
let starttab = tabpagenr()
" go to the heading's file
let file = s:agenda_files_copy[str2nr(matchstr(thisline, '^\d\d\d'))]
let lineno = str2nr(matchstr(thisline,'^\d\d\d\zs\d*'))
call org#LocateFile(file)
let save_cursor2 = getpos(".")
let newhead = matchstr(s:GetPlacedSignsString(bufnr("%")),'line=\zs\d\+\ze\s\+id=' . lineno)
let newhead = s:OrgGetHead_l(newhead)
execute newhead
if cycle_todo
" do todo operation
if a:0 >= 2
silent call s:ReplaceTodo(newtodo)
else
silent call s:ReplaceTodo()
endif
"normal V
"redraw
"sleep 100m
"normal V
else
" get the heading's text block
let lastline = s:OrgNextHead_l(newhead) - 1
if lastline > newhead
let g:text = getline(newhead,lastline)
elseif lastline == -1
let g:text = getline(newhead,line('$'))
else
let g:text = []
endif
endif
call setpos(".",save_cursor2)
" now go back to agenda
execute 'tabnext ' . starttab
execute bufwinnr('Agenda').'wincmd w'
if !cycle_todo
call append(line("."),g:text)
endif
else
" we're dealing with toggle of agenda heading that already
" has main buffer heading text in agenda. . .
normal j
let firstline = line(".")
let daytextpat = '^\S\+\s\+\d\{1,2}\s\S\+\s\d\d\d\d'
while (getline(line(".")) !~ '^\d\+\s\+') && (line(".") != line("$"))
\ && (getline(line(".")) !~ daytextpat)
\ && (getline(line(".")) !~ '\d empty days omitted')
normal j
endwhile
let lastline = line(".")
if (lastline < line("$")) ||
\ ( (getline(line(".")) =~ '^\d\+\s\+')
\ || (getline(line(".")) =~ daytextpat)
\ || (getline(line(".")) =~ '\d empty days omitted'))
let lastline = line(".") - 1
endif
call setpos(".",save_cursor)
" see if it there are changes that need to be
" pushed back to main buffer
call s:AgendaPutText()
silent execute firstline . ', ' . lastline . 'd'
endif
else
echo "You're not on a headline line."
endif
call setpos(".",save_cursor)
if cycle_todo
" we did cycle in main buffer, now do in agenda
if a:0 >= 2
silent call s:ReplaceTodo(s:last_newtodo)
else
silent call s:ReplaceTodo(s:last_newtodo)
endif
echo "Todo cycled."
endif
endfunction
function! s:MoveToHeadingFromAgenda(agenda_line)
"given line from agenda, go to the associated file and heading
let thisline = getline(a:agenda_line)
let file = s:agenda_files_copy[str2nr(matchstr(thisline, '^\d\d\d'))]
let lineno = str2nr(matchstr(thisline,'^\d\d\d\zs\d*'))
call org#LocateFile(file)
" need to check sign at this lineno, since for date agenda we're not necessarily at heading
let newhead = matchstr(s:GetPlacedSignsString(bufnr("%")),'line=\zs\d\+\ze\s\+id=' . lineno)
let newhead = s:OrgGetHead_l(newhead)
execute newhead
endfunction
function! s:IsVisibleHeading(line)
" returns 1 if line is of a visible heading,
" 0 if not
" a heading is visible if foldclosed = -1
" (i.e., it's not in a fold)
" OR if it's not in an earlier-started fold
" (i.e. start of fold heading is in is
" same as line of heading)
" *************************** the second and third lines of if
" statement are necessary because of bug where foldclosed is less
" than a head even though it is the fold head ***************
let fc = foldclosed(a:line)
if ((a:line > 0) && (fc == -1)) || (fc == a:line)
\ || ((fc < a:line) && s:IsText(fc) )
\ || ((fc < a:line) && (foldclosedend(fc) < a:line) )
" \ || (s:Ind(a:line) == 2)
return 1
else
return 0
endif
endfunction
function! OrgSingleHeadingText(operation)
" expand or collapse all visible Body Text
" under Heading fold that cursor is in
" operation: "collapse" or "expand"
" expand or collapse all Body Text
" currently visible under current heading
let l:startline = line(".")
let l:endline = s:OrgSubtreeLastLine_l(l:startline) - 1
call OrgBodyTextOperation(l:startline,l:endline,a:operation)
endfunction
function! s:StarLevelFromTo(from, to)
let save_cursor = getpos(".")
set fdm=manual
let b:v.levelstars = a:to
ChangeSyn
g/^\*\+/call setline(line("."),substitute(getline(line(".")),'^\*\+','*' .
\ repeat('*',(len(matchstr(getline(line(".")),'^\*\+')) - 1) * a:to / a:from),''))
set fdm=expr
call setpos(".",save_cursor)
endfunction
function! s:StarsForLevel(level)
return 1 + (a:level - 1) * b:v.levelstars
endfunction
function! s:OrgExpandLevelText(startlevel, endlevel)
" expand regular text for headings by level
let save_cursor = getpos(".")
normal gg
let startlevel = s:StarsForLevel(a:startlevel)
let endlevel = s:StarsForLevel(a:endlevel)
let l:mypattern = substitute(b:v.headMatchLevel,'level', startlevel . ',' . endlevel, "")
while search(l:mypattern, 'cW') > 0
execute line(".") + 1
while getline(line(".")) =~ b:v.drawerMatch
execute line(".") + 1
normal! j
endwhile
if s:IsText(line("."))
normal zv
endif
"normal l
endwhile
call setpos('.',save_cursor)
endfunction
" just an idea using 'global' not used anywhere yet
" visible is problem, must operate only on visible, doesn't do ths now
function! s:BodyTextOperation3(startline,endline, operation)
let l:oldcursor = line(".")
let nh = 0
call cursor(a:startline,0)
g/\*\{4,}/s:DoAllTextFold(line("."))
call cursor(l:oldcursor,0)
endfunction
function! OrgBodyTextOperation(startline,endline, operation)
" expand or collapse all Body Text from startline to endline
" operation: "collapse" or "expand"
" save original line
let l:oldcursor = line(".")
let nh = 0
" go to startline
call cursor(a:startline,0)
" travel from start to end operating on any
while 1
if getline(line(".")) =~ b:v.headMatch
if a:operation ==? "collapse"
call s:DoAllTextFold(line("."))
elseif a:operation ==? 'expand'
normal zv
endif
"elseif s:IsText(line(".")+1) && foldclosed(line(".")) == line(".")
"elseif foldclosed(line(".")) == line(".")
" "echo 'in expand area'
" if a:operation ==? 'expand'
" normal zv
" endif
endif
let lastnh = nh
let nh = s:NextVisibleHead(line("."))
"echo 'last ' . lastnh . ' now ' . nh
if (nh == 0) || (nh >= a:endline) || (nh == lastnh)
"echo "hit break"
break
elseif lastnh == nh
break
echo "bad exit from BodyTextOp"
else
"echo "hit ex"
execute nh
endif
endwhile
" now go back to original line position in buffer
call cursor(l:oldcursor,0)
endfunction
let g:calendar_sign = 'OrgCalSign'
function! OrgCalSign(day, month, year)
if a:year .'-'.s:Pre0(a:month).'-'.s:Pre0(a:day) ==? s:org_cal_date
return 1
else
return 0
endif
endfunction
function! OrgSetLine(line, file, newtext)
let save_cursor = getpos(".")
let curfile = expand("%:t")
call org#LocateFile(a:file)
call setline(a:line,a:newtext)
call org#LocateFile(curfile)
call setpos('.',save_cursor)
endfunction
function! OrgGetLine(line, file)
let save_cursor = getpos(".")
let curfile = expand("%:t")
call org#LocateFile(a:file)
let result = getline(a:line)
call org#LocateFile(curfile)
call setpos('.',save_cursor)
return result
endfunction
function! OrgAgendaDateType()
" return type of date line in Agenda
let text = getline(line('.'))[19:29]
if text =~ 'Sched'
let result = 'Scheduled'
elseif text =~ '\(In \|DEADLINE\)'
let result = 'Deadline'
elseif text =~ 'Closed'
let result = 'Closed'
elseif text =~ '('
let result = 'Range'
else
let result = 'Regular'
endif
return result
endfunction
function! GetDateAtCursor()
return matchstr( GetDateSpecAtCursor() , '^[[<]\zs\d\d\d\d-\d\d-\d\d' )
endfunction
function! GetDateSpecAtCursor()
let savecursor = getpos(".")
" save visual bell settings so no bell
" when not found"
let orig_vb = &vb
let orig_t_vb = &t_vb
set vb t_vb=
" check for date string within brackets
normal! va<
silent! normal! "xy
call setpos('.',savecursor)
if len(@x) < 7
"normal! vi["xy
normal! va[
silent! normal! "xy
endif
if (len(@x)>=15) && (len(@x)<41)
let date = matchstr(@x,'^[[<]\d\d\d\d-\d\d-\d\d')
else
let date = ''
endif
" restore visual bell settings
let &vb = orig_vb
let &t_vb = orig_t_vb
if date ># ''
" return with only opening '<' or '['
return @x
else
return ''
endif
call setpos(".", savecursor)
endfunction
function! CalEdit( sdate, stime )
" bring up calendar to edit and return a date value
call org#SaveLocation()
let basedate = a:sdate ==# '' ? s:Today() : a:sdate
let basetime = a:stime
let newdate = '<' . basedate[0:9] . ' ' . calutil#dayname(basedate[0:9]) . (basetime ># '' ? ' ' . basetime : '') . '>'
let newtime = basetime
hi Cursor guibg=black
let s:org_cal_date = newdate[1:10]
call Calendar(1,newdate[1:4],str2nr(newdate[6:7]))
" highlight chosen dates in calendar
hi Ag_Date guifg=red
call matchadd('Ag_Date','+\s\{0,1}\d\+')
redraw
let g:calendar_action='<SNR>'.s:SID().'_CalendarInsertDate'
let cue = ''
while 1
echohl LineNr | echon 'Date+time ['.basedate . ' '.basetime.']: '
"echohl None | echon cue.'_ =>' | echohl WildMenu | echon ' '.newdate[:-2] . ' ' . newtime
echohl None | echon cue.'_ =>' | echohl WildMenu | echon ' '.newdate[:-2] . '>'
let nchar = getchar()
let newchar = nr2char(nchar)
if newdate !~ 'interpret'
let curdif = calutil#jul(newdate[1:10])-calutil#jul(s:Today())
endif
if (nchar ==? "\<BS>") && (len(cue)>0)
let cue = cue[:-2]
elseif nchar ==? "\<s-right>"
let cue = ((curdif+1>=0) ?'+':'').(curdif+1).'d'
elseif nchar ==? "\<s-left>"
let cue = ((curdif-1>=0) ?'+':'').(curdif-1).'d'
elseif nchar ==? "\<s-down>"
let cue = ((curdif+7>=0) ?'+':'').(curdif+7).'d'
elseif nchar ==? "\<s-up>"
let cue = ((curdif-7>=0) ?'+':'').(curdif-7).'d'
elseif nchar ==? "\<c-down>"
let cue = ((curdif+30>=0) ?'+':'').(curdif+30).'d'
elseif nchar ==? "\<c-up>"
let cue = ((curdif-30>=0) ?'+':'').(curdif-30).'d'
elseif nchar ==? "\<s-c-down>"
let cue = ((curdif+365>=0) ?'+':'').(curdif+365).'d'
elseif nchar ==? "\<s-c-up>"
let cue = ((curdif-365>=0) ?'+':'').(curdif-365).'d'
elseif newchar ==? "\<cr>"
break
elseif newchar ==? "\<Esc>"
hi Cursor guibg=gray
if bufwinnr('__Calendar') > 0
bdelete Calendar
endif
redraw
return ''
elseif (nchar ==? "\<LeftMouse>") && (v:mouse_win > 0) && (bufwinnr('__Calendar') == v:mouse_win)
let g:cal_list=[]
exe v:mouse_win . "wincmd w"
exe v:mouse_lnum
exe "normal " . v:mouse_col."|"
normal
if g:cal_list != []
if newtime ># ''
let timespec = newtime
else
let timespec = matchstr(newdate,'\S\+:.*>')
endif
let newdate = '<'.g:cal_list[0].'-'.s:Pre0(g:cal_list[1]).'-'.s:Pre0(g:cal_list[2]) . ' '
let newdate .= calutil#dayname( g:cal_list[0].'-'.g:cal_list[1].'-'.g:cal_list[2])
let newdate .= timespec ># '' ? ' ' . timespec : ''.'>'
break
endif
else
let cue .= newchar
endif
try
let newdate = '<' . s:GetNewDate(cue,basedate,basetime) . '>'
catch
" don't raise error if user mistypes cue. . .
" or if last char makes cue uninterpretable
let newdate = "can't interpret date cue "
endtry
if g:org_use_calendar && (match(newdate,'\d\d\d\d-\d\d')>=0)
let s:org_cal_date = newdate[1:10]
call Calendar(1,newdate[1:4],str2nr(newdate[6:7]))
endif
echon repeat(' ',72)
redraw
endwhile
hi Cursor guibg=gray
bdelete __Calendar
call org#RestoreLocation()
return newdate
endfunction
command! OrgColumns :call OrgColumnsDashboard()
function! OrgColumnsDashboard(...)
let key = (a:0==1) ? a:1 : ''
let save_cursor = getpos('.')
if !exists('w:v.columnview')
let w:v={'columnview':0}
let w:v.org_item_len=100
let w:v.org_colview_list = []
let w:v.org_current_columns = ''
let w:v.org_column_item_head = ''
endif
if !exists('b:v.org_columns_show_headings')
let b:v.org_columns_show_headings = 0
endif
let force_all = 0
echohl WarningMsg
let save_more = &more
set nomore
while 1
if key ==# ''
echohl MoreMsg
echo "=========================================="
echo " Buffer default columns: " . b:v.buffer_columns
echo " Current default columns: " . w:v.org_current_columns
echo " Column view is currently: " . (w:v.columnview==1 ? 'ON' : 'OFF')
echo " Show column headers is currently: " . (b:v.org_columns_show_headings ? 'ON' : 'OFF')
echo " Heading line count is currently: " . (g:org_show_fold_lines==1 ? 'ON' : 'OFF')
if (w:v.columnview == 0) && (force_all == 1)
echo " NEXT CHOICE WILL BE APPLIED TO ENTIRE BUFFER"
endif
echo " "
echo " Press key to enter a columns command"
echo " ------------------------------------"
if (w:v.columnview == 0) && (force_all == 0)
echo " f force all of buffer to use chosen columns"
endif
if w:v.org_current_columns != b:v.buffer_columns
echo " r revert to buffer default columns"
endif
echo " t toggle column view on/off"
echo " h toggle show headings on/off"
echo " l line count on/off"
if len(g:org_custom_column_options) > 0
echo " Custom columns settings:"
endif
let i = 0
while i < len(g:org_custom_column_options)
echo " " . i . " " . g:org_custom_column_options[i]
let i += 1
endwhile
echo " ------------------------------------"
echo " "
echohl Question
let key = nr2char(getchar())
redraw
endif
if key ==? 'f'
let force_all = 1
redraw
continue
endif
let master_head = (force_all == 1 ) ? 0 : line('.')
if key ==? 'r'
let w:v.org_current_columns = b:v.buffer_columns
if w:v.columnview == 1
"turn off col view
call ToggleColumnView(master_head, w:v.org_current_columns)
endif
call ToggleColumnView(master_head, w:v.org_current_columns)
elseif key ==? 't'
" current columns will get set in SetColumnHeads()
call ToggleColumnView(master_head,'')
elseif key ==? 'h'
let b:v.org_columns_show_headings = 1 - b:v.org_columns_show_headings
elseif key ==? 'l'
let g:org_show_fold_lines = 1 - g:org_show_fold_lines
elseif key =~ '[0-9]'
let w:v.org_current_columns = g:org_custom_column_options[key]
if w:v.columnview == 1
" turn off
call ToggleColumnView(master_head, w:v.org_current_columns)
endif
call ToggleColumnView(master_head, w:v.org_current_columns)
else
echo "No column option selected."
endif
break
endwhile
if b:v.org_columns_show_headings == 0
call s:ColHeadWindow('',0)
elseif (w:v.columnview == 1) && (bufnr('ColHeadBuffer') == -1)
call s:ColHeadWindow(w:v.org_column_item_head)
endif
echohl None
let &more = save_more
call s:AdjustItemLen()
" redraw folded headings
setlocal foldtext=OrgFoldText()
call setpos('.',save_cursor)