Commits

abudden committed 17f3cf7

Implementation of handlers for passing dictionaries between Vim and Python.

Comments (0)

Files changed (6)

 
 .*.swp
 *.pyc
+_.swp
 types_*.taghl
 doc/tags
 sh.exe.stackdump

autoload/TagHighlight/RunPythonScript.vim

 	return result
 endfunction
 
+function! s:GetVarType(value)
+	if type(a:value) == type(0)
+		return "int"
+	elseif type(a:value) == type("")
+		return "string"
+	elseif type(a:value) == type([])
+		return "list"
+	elseif type(a:value) == type({})
+		return "dict"
+	elseif type(a:value) == type(function("tr"))
+		return "function"
+	elseif type(a:value) == type(0.0)
+		return "float"
+	endif
+endfunction
+
+function! s:SetPyVariable(PY, pyoption, type, value)
+	let handled_option = 0
+	if a:type == 'bool'
+		let handled_option = 1
+		if (a:value == 1) || (a:value == 'True')
+			exe a:PY a:pyoption '= True'
+		else
+			exe a:PY a:pyoption '= False'
+		endif
+	elseif a:type == 'string'
+		let handled_option = 1
+		exe a:PY a:pyoption '= r"""'.a:value.'"""'
+	elseif a:type == 'int'
+		let handled_option = 1
+		exe a:PY a:pyoption '= ' . a:value
+	elseif a:type == 'list'
+		let handled_option = 1
+		exe a:PY a:pyoption '= []'
+		for entry in a:value
+			exe a:PY a:pyoption '+= [r"""' . entry . '"""]'
+		endfor
+	elseif a:type == 'dict'
+		let handled_option = 1
+		exe a:PY a:pyoption '= {}'
+		for key in keys(a:value)
+			call s:SetPyVariable(a:PY,
+						\ a:pyoption.'[r"""'.key.'"""]',
+						\ s:GetVarType(a:value[key]),
+						\ a:value[key])
+		endfor
+	endif
+	return handled_option
+endfunction
+
 function! TagHighlight#RunPythonScript#RunGenerator(options)
 	" Will only actually load the options once
 	call TagHighlight#Option#LoadOptions()
 						\ has_key(a:options, option['Destination'])
 				" We can handle this one automatically
 				let pyoption = 'options["'.option['Destination'].'"]'
-				if option['Type'] == 'bool'
+				let result = s:SetPyVariable(PY, pyoption,
+							\ option['Type'],
+							\ a:options[option['Destination']])
+				if result != 0
 					let handled_options += [option['Destination']]
-					let value = a:options[option['Destination']]
-					if (value == 1) || (value == 'True')
-						exe PY pyoption '= True'
-					else
-						exe PY pyoption '= False'
-					endif
-				elseif option['Type'] == 'string'
-					let handled_options += [option['Destination']]
-					exe PY pyoption '= r"""'.a:options[option['Destination']].'"""'
-				elseif option['Type'] == 'int'
-					let handled_options += [option['Destination']]
-					exe PY pyoption '= ' . a:options[option['Destination']]
-				elseif option['Type'] == 'list'
-					let handled_options += [option['Destination']]
-					exe PY pyoption '= []'
-					for entry in a:options[option['Destination']]
-						exe PY pyoption '+= [r"""' . entry . '"""]'
-					endfor
 				endif
 			endif
 		endfor
 							let args += [switch, entry]
 						endif
 					endfor
+				elseif option['Type'] == 'dict'
+					" Not sure how robust this is likely to be...
+					" or for that matter how likely it is that the result
+					" will be the same as the if_pyth version...
+					let args += [switch, string(a:options[option['Destination']])]
 				endif
 			endif
 		endfor

plugin/TagHighlight/data/options.txt

 	CommandLineSwitches:--language-tag-types
 	Type:dict
 	Default:{}
-	Help:Explicit filter on tag types for a given language
+	Help:Explicit filter on tag types for a given language (pass as key:value or key:value,value,value).
 
 DebugPrintTime:
 	CommandLineSwitches:--print-time-with-debug

plugin/TagHighlight/module/cmd.py

 
 from .config import SetInitialOptions, LoadLanguages
 from .options import AllOptions
+import ast
+
+def DictHandler(option, opt_str, value, parser):
+    setattr(parser.values, option.dest, ast.literal_eval(value))
 
 def ProcessCommandLine():
     parser = optparse.OptionParser()
                     default='DEFAULT_OPTION_USED',
                     dest=dest,
                     help=AllOptions[dest]['Help'])
+        elif AllOptions[dest]['Type'] == 'dict':
+            parser.add_option(*AllOptions[dest]['CommandLineSwitches'],
+                    action="callback",
+                    type="string",
+                    default='DEFAULT_OPTION_USED',
+                    dest=dest,
+                    callback=DictHandler,
+                    help=AllOptions[dest]['Help'])
         else:
             optparse_type='string'
             if AllOptions[dest]['Type'] in ['string', 'int']:

plugin/TagHighlight/module/generation.py

 # ---------------------------------------------------------------------
 from __future__ import print_function
 import os
+import sys
 import re
 from .utilities import GenerateValidKeywordRange, IsValidKeyword
 from .debug import Debug
         'skipempty'
         ]
 
+def write(fh, value):
+    fh.write(value.encode('ascii'))
+
 def CreateTypesFile(options, language, unscoped_tags, file_tags):
     Debug("Writing types file", "Information")
 
     entry_sets = {}
 
-    for source_file in [None] + file_tags.keys():
+    for source_file in [None] + list(file_tags.keys()):
         if source_file is None:
             tags = unscoped_tags
         else:
         sys.exit(1)
 
     try:
-        for source_file in [None] + entry_sets.keys():
+        for source_file in [None] + list(entry_sets.keys()):
             if source_file is None:
                 vimtypes_entries = unscoped_entries
                 prefix = ''
 
             if source_file is not None and not options['IgnoreFileScope']:
                 formatted_file = os.path.normpath(source_file).replace(os.path.sep, '/')
-                fh.write('" Matches for file %s:\n' % source_file)
-                fh.write('if (has_key(b:TagHighlightPrivate, "NormalisedPath") && b:TagHighlightPrivate["NormalisedPath"] == "%s") || TagHighlight#Option#GetOption("IgnoreFileScope")\n' % formatted_file)
+                write(fh, '" Matches for file %s:\n' % source_file)
+                write(fh, 'if (has_key(b:TagHighlightPrivate, "NormalisedPath") && b:TagHighlightPrivate["NormalisedPath"] == "%s") || TagHighlight#Option#GetOption("IgnoreFileScope")\n' % formatted_file)
             for line in vimtypes_entries:
                 try:
-                    fh.write(prefix + line.encode('ascii'))
+                    write(fh, prefix + line)
                 except UnicodeDecodeError:
                     Debug("Error decoding line '{0!r}'".format(line), "Error")
-                    fh.write('echoerr "Types generation error"\n'.encode('ascii'))
-                fh.write('\n'.encode('ascii'))
+                    write(fh, 'echoerr "Types generation error"\n')
+                write(fh, '\n')
             if source_file is not None and not options['IgnoreFileScope']:
-                fh.write('endif\n')
+                write(fh, 'endif\n')
     except IOError:
         Debug("ERROR: Couldn't write {file} contents\n".format(file=outfile), "Error")
         sys.exit(1)

plugin/TagHighlight/module/worker.py

     Debug("Release:" + config['Release'], "Information")
     Debug("Version:" + repr(config['Version']), "Information")
     Debug("Options:" + repr(options), "Information")
+    Debug("Manually Set:" + repr(manually_set), "Information")
 
     tag_file_absolute = os.path.join(config['CtagsFileLocation'], config['TagFileName'])
     if config['DoNotGenerateTags'] and not os.path.exists(tag_file_absolute):