diff --git a/README.md b/README.md index 6ab0dc9..a67f64f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ -[![Build Status](https://travis-ci.org/jessevdk/cldoc.svg?branch=master)](https://travis-ci.org/jessevdk/cldoc) - -cldoc is a clang based documentation generator for C and C++. cldoc tries to +markdoc is a fork of cldoc, a clang based documentation generator for C and C++. cldoc tries to solve the issue of writing C/C++ software documentation with a modern, non-intrusive and robust approach. +markdoc produces markdown _output_ intended for jekyll-based static sites such as GitHub pages. # Features * Uses clang to robustly parse even the most complex C++ projects without diff --git a/cldoc.pyproj b/cldoc.pyproj new file mode 100644 index 0000000..38a3aaf --- /dev/null +++ b/cldoc.pyproj @@ -0,0 +1,128 @@ + + + + Debug + 2.0 + {91ab4796-69d9-421c-b7a7-544a473f214b} + + scripts\test.py + ..\..\..\..\..\Python36;..\..\..\..\..\Python36\Scripts + . + . + {888888a0-9f3d-457c-b088-3a5042f75d52} + Standard Python launcher + generate -IC:\\Simul\\4.2 -I"$(VCINSTALLDIR)\\atlmfc\\include" -I"$(VCINSTALLDIR)\\include" -I"C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.10240.0\\ucrt" -I"C:\\Program Files\\LLVM\\lib\\clang\\6.0.0\\include" -std=c++1y -fms-extensions -fms-compatibility -fms-compatibility-version=19 -Wno-deprecated-declarations -Wno-ignored-attributes -Wno-microsoft-template -D_MSC_VER=1900 -DDOXYGEN=1 -- --type=md --loglevel=info --output C:/Simul/docs --strip "$(SIMUL)/" --md_output ref $(SIMUL)/Base/*.h $(SIMUL)/Clouds/*.h $(SIMUL)/Sky/*.h $(SIMUL)/Terrain/*.h --merge "C:/Simul/4.2/Simul/Help/*.md" --clean C:/Simul/docs/ref --post "$(SIMUL)/Help/build.bat" + + + False + Path=C:\Program Files\LLVM\bin;$(Path) +also= +test= + + + False + Global|PythonCore|3.7 + + + + + 10.0 + + + + + + + + + + + + + + Code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Code + + + + + + + + Code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/cldoc.sln b/cldoc.sln new file mode 100644 index 0000000..cc63a8b --- /dev/null +++ b/cldoc.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25123.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "cldoc", "cldoc.pyproj", "{91AB4796-69D9-421C-B7A7-544A473F214B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {91AB4796-69D9-421C-B7A7-544A473F214B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {91AB4796-69D9-421C-B7A7-544A473F214B}.Release|Any CPU.ActiveCfg = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/cldoc/__init__.py b/cldoc/__init__.py index 69f6a85..0899bce 100644 --- a/cldoc/__init__.py +++ b/cldoc/__init__.py @@ -14,58 +14,39 @@ import sys -def run_inspect(args): - from . import cmdinspect - cmdinspect.run(args) - -def run_serve(args): - from . import cmdserve - cmdserve.run(args) - def run_generate(args): - from . import cmdgenerate - cmdgenerate.run(args) - -def run_gir(args): - from . import cmdgir - cmdgir.run(args) + from . import cmdgenerate + cmdgenerate.run(args) def print_available_commands(): - sys.stderr.write('Available commands:\n') + sys.stderr.write('Available commands:\n') - commands = ['inspect', 'serve', 'generate', 'gir'] + commands = ['inspect', 'serve', 'generate', 'gir'] - for c in commands: - sys.stderr.write(' ' + c + '\n') + for c in commands: + sys.stderr.write(' ' + c + '\n') - sys.stderr.write('\n') + sys.stderr.write('\n') def run(): - if len(sys.argv) <= 1: - sys.stderr.write('Please use: cldoc [command] [OPTIONS] [FILES...]\n\n') - print_available_commands() - sys.exit(1) - - cmd = sys.argv[1] - rest = sys.argv[2:] - - if cmd == 'inspect': - run_inspect(rest) - elif cmd == 'serve': - run_serve(rest) - elif cmd == 'generate': - run_generate(rest) - elif cmd == 'gir': - run_gir(rest) - elif cmd == '--help' or cmd == '-h': - sys.stderr.write('Please use: cldoc [command] --help\n\n') - print_available_commands() - sys.exit(1) - else: - sys.stderr.write('Unknown command `{0}\'\n'.format(cmd)) - sys.exit(1) + if len(sys.argv) <= 1: + sys.stderr.write('Please use: cldoc [command] [OPTIONS] [FILES...] or cldoc file.markdoc\n\n') + print_available_commands() + sys.exit(1) + + cmd = sys.argv[1] + rest = sys.argv[2:] + if cmd == 'generate': + run_generate(rest) + elif cmd == '--help' or cmd == '-h': + sys.stderr.write('Please use: cldoc [command] --help\n\n') + print_available_commands() + sys.exit(1) + else: + sys.stderr.write('Unknown command `{0}\'\n'.format(cmd)) + sys.exit(1) if __name__ == '__main__': - run() + run() # vi:ts=4:et diff --git a/cldoc/clang/__init__.py b/cldoc/clang/__init__.py index 88f3081..2defb69 100644 --- a/cldoc/clang/__init__.py +++ b/cldoc/clang/__init__.py @@ -1,6 +1,6 @@ #===- __init__.py - Clang Python Bindings --------------------*- python -*--===# # -# The LLVM Compiler Infrastructure +# The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. @@ -17,7 +17,7 @@ cindex - Bindings for the Clang indexing library. + Bindings for the Clang indexing library. """ __all__ = ['cindex'] diff --git a/cldoc/clang/cindex.py b/cldoc/clang/cindex.py index e58a2dd..3abb8fb 100644 --- a/cldoc/clang/cindex.py +++ b/cldoc/clang/cindex.py @@ -12,7 +12,7 @@ # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. #===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# # -# The LLVM Compiler Infrastructure +# The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. @@ -38,20 +38,20 @@ Index - The top-level object which manages some global library state. + The top-level object which manages some global library state. TranslationUnit - High-level object encapsulating the AST for a single translation unit. These - can be loaded from .ast files or parsed on the fly. + High-level object encapsulating the AST for a single translation unit. These + can be loaded from .ast files or parsed on the fly. Cursor - Generic object for representing a node in the AST. + Generic object for representing a node in the AST. SourceRange, SourceLocation, and File - Objects representing information about the input source. + Objects representing information about the input source. Most object information is exposed using properties, when the underlying API call is efficient. @@ -81,59 +81,59 @@ import sys if sys.version_info[0] == 3: - # Python 3 strings are unicode, translate them to/from utf8 for C-interop. - class c_interop_string(c_char_p): - - def __init__(self, p=None): - if p is None: - p = "" - if isinstance(p, str): - p = p.encode("utf8") - super(c_char_p, self).__init__(p) - - def __str__(self): - return self.value - - @property - def value(self): - if super(c_char_p, self).value is None: - return None - return super(c_char_p, self).value.decode("utf8") - - @classmethod - def from_param(cls, param): - if isinstance(param, str): - return cls(param) - if isinstance(param, bytes): - return cls(param) - if param is None: - # Support passing null to C functions expecting char arrays - return None - raise TypeError("Cannot convert '{}' to '{}'".format(type(param).__name__, cls.__name__)) - - @staticmethod - def to_python_string(x, *args): - return x.value - - def b(x): - if isinstance(x, bytes): - return x - return x.encode('utf8') - - xrange = range + # Python 3 strings are unicode, translate them to/from utf8 for C-interop. + class c_interop_string(c_char_p): +# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper + def __init__(self, p=None): + if p is None: + p = "" + if isinstance(p, str): + p = p.encode("utf8") + super(c_char_p, self).__init__(p) +# object. This is a problem, because it means that from_parameter will see an + def __str__(self): + return self.value +# integer and pass the wrong value on platforms where int != void*. Work around + @property + def value(self): + if super(c_char_p, self).value is None: + return None + return super(c_char_p, self).value.decode("utf8") +# this by marshalling object arguments as void**. + @classmethod + def from_param(cls, param): + if isinstance(param, str): + return cls(param) + if isinstance(param, bytes): + return cls(param) + if param is None: + # Support passing null to C functions expecting char arrays + return None + raise TypeError("Cannot convert '{}' to '{}'".format(type(param).__name__, cls.__name__)) + + @staticmethod + def to_python_string(x, *args): + return x.value + + def b(x): + if isinstance(x, bytes): + return x + return x.encode('utf8') + + xrange = range elif sys.version_info[0] == 2: - # Python 2 strings are utf8 byte strings, no translation is needed for - # C-interop. - c_interop_string = c_char_p + # Python 2 strings are utf8 byte strings, no translation is needed for + # C-interop. + c_interop_string = c_char_p - def _to_python_string(x, *args): - return x + def _to_python_string(x, *args): + return x - c_interop_string.to_python_string = staticmethod(_to_python_string) + c_interop_string.to_python_string = staticmethod(_to_python_string) - def b(x): - return x + def b(x): + return x # ctypes doesn't implicitly convert c_void_p to the appropriate wrapper @@ -147,570 +147,580 @@ def b(x): ### Exception Classes ### class TranslationUnitLoadError(Exception): - """Represents an error that occurred when loading a TranslationUnit. + """Represents an error that occurred when loading a TranslationUnit. - This is raised in the case where a TranslationUnit could not be - instantiated due to failure in the libclang library. + This is raised in the case where a TranslationUnit could not be + instantiated due to failure in the libclang library. - FIXME: Make libclang expose additional error information in this scenario. - """ - pass + FIXME: Make libclang expose additional error information in this scenario. + """ + pass class TranslationUnitSaveError(Exception): - """Represents an error that occurred when saving a TranslationUnit. + """Represents an error that occurred when saving a TranslationUnit. - Each error has associated with it an enumerated value, accessible under - e.save_error. Consumers can compare the value with one of the ERROR_ - constants in this class. - """ + Each error has associated with it an enumerated value, accessible under + e.save_error. Consumers can compare the value with one of the ERROR_ + constants in this class. + """ - # Indicates that an unknown error occurred. This typically indicates that - # I/O failed during save. - ERROR_UNKNOWN = 1 + # Indicates that an unknown error occurred. This typically indicates that + # I/O failed during save. + ERROR_UNKNOWN = 1 - # Indicates that errors during translation prevented saving. The errors - # should be available via the TranslationUnit's diagnostics. - ERROR_TRANSLATION_ERRORS = 2 + # Indicates that errors during translation prevented saving. The errors + # should be available via the TranslationUnit's diagnostics. + ERROR_TRANSLATION_ERRORS = 2 - # Indicates that the translation unit was somehow invalid. - ERROR_INVALID_TU = 3 + # Indicates that the translation unit was somehow invalid. + ERROR_INVALID_TU = 3 - def __init__(self, enumeration, message): - assert isinstance(enumeration, int) + def __init__(self, enumeration, message): + assert isinstance(enumeration, int) + if enumeration < 1 or enumeration > 3: + raise Exception("Encountered undefined TranslationUnit save error " + "constant: %d. Please file a bug to have this " + "value supported." % enumeration) - if enumeration < 1 or enumeration > 3: - raise Exception("Encountered undefined TranslationUnit save error " - "constant: %d. Please file a bug to have this " - "value supported." % enumeration) - - self.save_error = enumeration - Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) + self.save_error = enumeration + Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) ### Structures and Utility Classes ### class CachedProperty(object): - """Decorator that lazy-loads the value of a property. + """Decorator that lazy-loads the value of a property. - The first time the property is accessed, the original property function is - executed. The value it returns is set as the new value of that instance's - property, replacing the original method. - """ + The first time the property is accessed, the original property function is + executed. The value it returns is set as the new value of that instance's + property, replacing the original method. + """ - def __init__(self, wrapped): - self.wrapped = wrapped - try: - self.__doc__ = wrapped.__doc__ - except: - pass + def __init__(self, wrapped): + self.wrapped = wrapped + try: + self.__doc__ = wrapped.__doc__ + except: + pass - def __get__(self, instance, instance_type=None): - if instance is None: - return self + def __get__(self, instance, instance_type=None): + if instance is None: + return self - value = self.wrapped(instance) - setattr(instance, self.wrapped.__name__, value) + value = self.wrapped(instance) + setattr(instance, self.wrapped.__name__, value) - return value + return value class _CXString(Structure): - """Helper for transforming CXString results.""" + """Helper for transforming CXString results.""" - _fields_ = [("spelling", c_char_p), ("free", c_int)] + _fields_ = [("spelling", c_char_p), ("free", c_int)] - def __del__(self): - conf.lib.clang_disposeString(self) + def __del__(self): + conf.lib.clang_disposeString(self) - @staticmethod - def from_result(res, fn=None, args=None): - assert isinstance(res, _CXString) - return conf.lib.clang_getCString(res) + @staticmethod + def from_result(res, fn=None, args=None): + assert isinstance(res, _CXString) + return conf.lib.clang_getCString(res) +class GenericLocation(): + def __init__(self,file,line,col): + self.file=file + self.line=line + self.column=col class SourceLocation(Structure): - """ - A SourceLocation represents a particular location within a source file. - """ - _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] - _data = None - - def _get_instantiation(self): - if self._data is None: - f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() - conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l), - byref(c), byref(o)) - if f: - f = File(f) - else: - f = None - self._data = (f, int(l.value), int(c.value), int(o.value)) - return self._data - - @staticmethod - def from_position(tu, file, line, column): - """ - Retrieve the source location associated with a given file/line/column in - a particular translation unit. - """ - return conf.lib.clang_getLocation(tu, file, line, column) - - @staticmethod - def from_offset(tu, file, offset): - """Retrieve a SourceLocation from a given character offset. - - tu -- TranslationUnit file belongs to - file -- File instance to obtain offset from - offset -- Integer character offset within file - """ - return conf.lib.clang_getLocationForOffset(tu, file, offset) - - @property - def file(self): - """Get the file represented by this source location.""" - return self._get_instantiation()[0] - - @property - def line(self): - """Get the line represented by this source location.""" - return self._get_instantiation()[1] - - @property - def column(self): - """Get the column represented by this source location.""" - return self._get_instantiation()[2] - - @property - def offset(self): - """Get the file offset represented by this source location.""" - return self._get_instantiation()[3] - - def __eq__(self, other): - return conf.lib.clang_equalLocations(self, other) - - def __ne__(self, other): - return not self.__eq__(other) - - def __repr__(self): - if self.file: - filename = self.file.name - else: - filename = None - return "" % ( - filename, self.line, self.column) + """ + A SourceLocation represents a particular location within a source file. + """ + _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] + _data = None + + def _get_instantiation(self): + if self._data is None: + f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() + #conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l),byref(c), byref(o)) + conf.lib.clang_getExpansionLocation(self, byref(f), byref(l),byref(c), byref(o)) + if f: + f = File(f) + else: + f = None + self._data = (f, int(l.value), int(c.value), int(o.value)) + return self._data + + @staticmethod + def from_position(tu, file, line, column): + """ + Retrieve the source location associated with a given file/line/column in + a particular translation unit. + """ + return conf.lib.clang_getLocation(tu, file, line, column) + @staticmethod + def from_file_line(file, line): + """ + Create a + """ + loc=GenericLocation(file,line,0) + return loc + @staticmethod + def from_offset(tu, file, offset): + """Retrieve a SourceLocation from a given character offset. + + tu -- TranslationUnit file belongs to + file -- File instance to obtain offset from + offset -- Integer character offset within file + """ + return conf.lib.clang_getLocationForOffset(tu, file, offset) + + @property + def file(self): + """Get the file represented by this source location.""" + return self._get_instantiation()[0] + + @property + def line(self): + """Get the line represented by this source location.""" + return self._get_instantiation()[1] + + @property + def column(self): + """Get the column represented by this source location.""" + return self._get_instantiation()[2] + + @property + def offset(self): + """Get the file offset represented by this source location.""" + return self._get_instantiation()[3] + + def __eq__(self, other): + return conf.lib.clang_equalLocations(self, other) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + if self.file: + filename = self.file.name + else: + filename = None + return "" % ( + filename, self.line, self.column) class SourceRange(Structure): - """ - A SourceRange describes a range of source locations within the source - code. - """ - _fields_ = [ - ("ptr_data", c_void_p * 2), - ("begin_int_data", c_uint), - ("end_int_data", c_uint)] - - # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes - # object. - @staticmethod - def from_locations(start, end): - return conf.lib.clang_getRange(start, end) - - @property - def start(self): - """ - Return a SourceLocation representing the first character within a - source range. - """ - return conf.lib.clang_getRangeStart(self) - - @property - def end(self): - """ - Return a SourceLocation representing the last character within a - source range. - """ - return conf.lib.clang_getRangeEnd(self) - - def __eq__(self, other): - return conf.lib.clang_equalRanges(self, other) - - def __ne__(self, other): - return not self.__eq__(other) - - def __contains__(self, other): - """Useful to detect the Token/Lexer bug""" - if not isinstance(other, SourceLocation): - return False - if other.file is None and self.start.file is None: - pass - elif ( self.start.file.name != other.file.name or - other.file.name != self.end.file.name): - # same file name - return False - # same file, in between lines - if self.start.line < other.line < self.end.line: - return True - elif self.start.line == other.line: - # same file first line - if self.start.column <= other.column: - return True - elif other.line == self.end.line: - # same file last line - if other.column <= self.end.column: - return True - return False - - def __repr__(self): - return "" % (self.start, self.end) + """ + A SourceRange describes a range of source locations within the source + code. + """ + _fields_ = [ + ("ptr_data", c_void_p * 2), + ("begin_int_data", c_uint), + ("end_int_data", c_uint)] + + # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes + # object. + @staticmethod + def from_locations(start, end): + return conf.lib.clang_getRange(start, end) + + @property + def start(self): + """ + Return a SourceLocation representing the first character within a + source range. + """ + return conf.lib.clang_getRangeStart(self) + + @property + def end(self): + """ + Return a SourceLocation representing the last character within a + source range. + """ + return conf.lib.clang_getRangeEnd(self) + + def __eq__(self, other): + return conf.lib.clang_equalRanges(self, other) + + def __ne__(self, other): + return not self.__eq__(other) + + def __contains__(self, other): + """Useful to detect the Token/Lexer bug""" + if not isinstance(other, SourceLocation): + return False + if other.file is None and self.start.file is None: + pass + elif ( self.start.file.name != other.file.name or + other.file.name != self.end.file.name): + # same file name + return False + # same file, in between lines + if self.start.line < other.line < self.end.line: + return True + elif self.start.line == other.line: + # same file first line + if self.start.column <= other.column: + return True + elif other.line == self.end.line: + # same file last line + if other.column <= self.end.column: + return True + return False + + def __repr__(self): + return "" % (self.start, self.end) class Diagnostic(object): - """ - A Diagnostic is a single instance of a Clang diagnostic. It includes the - diagnostic severity, the message, the location the diagnostic occurred, as - well as additional source ranges and associated fix-it hints. - """ - - Ignored = 0 - Note = 1 - Warning = 2 - Error = 3 - Fatal = 4 - - DisplaySourceLocation = 0x01 - DisplayColumn = 0x02 - DisplaySourceRanges = 0x04 - DisplayOption = 0x08 - DisplayCategoryId = 0x10 - DisplayCategoryName = 0x20 - _FormatOptionsMask = 0x3f - - def __init__(self, ptr): - self.ptr = ptr - - def __del__(self): - conf.lib.clang_disposeDiagnostic(self) - - @property - def severity(self): - return conf.lib.clang_getDiagnosticSeverity(self) - - @property - def location(self): - return conf.lib.clang_getDiagnosticLocation(self) - - @property - def spelling(self): - return conf.lib.clang_getDiagnosticSpelling(self) - - @property - def ranges(self): - class RangeIterator: - def __init__(self, diag): - self.diag = diag - - def __len__(self): - return int(conf.lib.clang_getDiagnosticNumRanges(self.diag)) - - def __getitem__(self, key): - if (key >= len(self)): - raise IndexError - return conf.lib.clang_getDiagnosticRange(self.diag, key) - - return RangeIterator(self) - - @property - def fixits(self): - class FixItIterator: - def __init__(self, diag): - self.diag = diag - - def __len__(self): - return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag)) - - def __getitem__(self, key): - range = SourceRange() - value = conf.lib.clang_getDiagnosticFixIt(self.diag, key, - byref(range)) - if len(value) == 0: - raise IndexError - - return FixIt(range, value) - - return FixItIterator(self) - - @property - def children(self): - class ChildDiagnosticsIterator: - def __init__(self, diag): - self.diag_set = conf.lib.clang_getChildDiagnostics(diag) - - def __len__(self): - return int(conf.lib.clang_getNumDiagnosticsInSet(self.diag_set)) - - def __getitem__(self, key): - diag = conf.lib.clang_getDiagnosticInSet(self.diag_set, key) - if not diag: - raise IndexError - return Diagnostic(diag) - - return ChildDiagnosticsIterator(self) - - @property - def category_number(self): - """The category number for this diagnostic or 0 if unavailable.""" - return conf.lib.clang_getDiagnosticCategory(self) - - @property - def category_name(self): - """The string name of the category for this diagnostic.""" - return conf.lib.clang_getDiagnosticCategoryText(self) - - @property - def option(self): - """The command-line option that enables this diagnostic.""" - return conf.lib.clang_getDiagnosticOption(self, None) - - @property - def format(self, options=-1): - if options == -1: - options = conf.lib.clang_defaultDiagnosticDisplayOptions() - - return conf.lib.clang_formatDiagnostic(self, options) - - @property - def disable_option(self): - """The command-line option that disables this diagnostic.""" - disable = _CXString() - conf.lib.clang_getDiagnosticOption(self, byref(disable)) - return _CXString.from_result(disable) - - def format(self, options=None): - """ - Format this diagnostic for display. The options argument takes - Diagnostic.Display* flags, which can be combined using bitwise OR. If - the options argument is not provided, the default display options will - be used. - """ - if options is None: - options = conf.lib.clang_defaultDiagnosticDisplayOptions() - if options & ~Diagnostic._FormatOptionsMask: - raise ValueError('Invalid format options') - return conf.lib.clang_formatDiagnostic(self, options) - - def __repr__(self): - return "" % ( - self.severity, self.location, self.spelling) - - def __str__(self): - return self.format() - - def from_param(self): - return self.ptr + """ + A Diagnostic is a single instance of a Clang diagnostic. It includes the + diagnostic severity, the message, the location the diagnostic occurred, as + well as additional source ranges and associated fix-it hints. + """ + + Ignored = 0 + Note = 1 + Warning = 2 + Error = 3 + Fatal = 4 + + DisplaySourceLocation = 0x01 + DisplayColumn = 0x02 + DisplaySourceRanges = 0x04 + DisplayOption = 0x08 + DisplayCategoryId = 0x10 + DisplayCategoryName = 0x20 + _FormatOptionsMask = 0x3f + + def __init__(self, ptr): + self.ptr = ptr + + def __del__(self): + conf.lib.clang_disposeDiagnostic(self) + + @property + def severity(self): + return conf.lib.clang_getDiagnosticSeverity(self) + + @property + def location(self): + return conf.lib.clang_getDiagnosticLocation(self) + + @property + def spelling(self): + return conf.lib.clang_getDiagnosticSpelling(self) + + @property + def ranges(self): + class RangeIterator: + def __init__(self, diag): + self.diag = diag + + def __len__(self): + return int(conf.lib.clang_getDiagnosticNumRanges(self.diag)) + + def __getitem__(self, key): + if (key >= len(self)): + raise IndexError + return conf.lib.clang_getDiagnosticRange(self.diag, key) + + return RangeIterator(self) + + @property + def fixits(self): + class FixItIterator: + def __init__(self, diag): + self.diag = diag + + def __len__(self): + return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag)) + + def __getitem__(self, key): + range = SourceRange() + value = conf.lib.clang_getDiagnosticFixIt(self.diag, key, + byref(range)) + if len(value) == 0: + raise IndexError + + return FixIt(range, value) + + return FixItIterator(self) + + @property + def children(self): + class ChildDiagnosticsIterator: + def __init__(self, diag): + self.diag_set = conf.lib.clang_getChildDiagnostics(diag) + + def __len__(self): + return int(conf.lib.clang_getNumDiagnosticsInSet(self.diag_set)) + + def __getitem__(self, key): + diag = conf.lib.clang_getDiagnosticInSet(self.diag_set, key) + if not diag: + raise IndexError + return Diagnostic(diag) + + return ChildDiagnosticsIterator(self) + + @property + def category_number(self): + """The category number for this diagnostic or 0 if unavailable.""" + return conf.lib.clang_getDiagnosticCategory(self) + + @property + def category_name(self): + """The string name of the category for this diagnostic.""" + return conf.lib.clang_getDiagnosticCategoryText(self) + + @property + def option(self): + """The command-line option that enables this diagnostic.""" + return conf.lib.clang_getDiagnosticOption(self, None) + + @property + def format(self, options=-1): + if options == -1: + options = conf.lib.clang_defaultDiagnosticDisplayOptions() + + return conf.lib.clang_formatDiagnostic(self, options) + + @property + def disable_option(self): + """The command-line option that disables this diagnostic.""" + disable = _CXString() + conf.lib.clang_getDiagnosticOption(self, byref(disable)) + return _CXString.from_result(disable) + + def format(self, options=None): + """ + Format this diagnostic for display. The options argument takes + Diagnostic.Display* flags, which can be combined using bitwise OR. If + the options argument is not provided, the default display options will + be used. + """ + if options is None: + options = conf.lib.clang_defaultDiagnosticDisplayOptions() + if options & ~Diagnostic._FormatOptionsMask: + raise ValueError('Invalid format options') + return conf.lib.clang_formatDiagnostic(self, options) + + def __repr__(self): + return "" % ( + self.severity, self.location, self.spelling) + + def __str__(self): + return self.format() + + def from_param(self): + return self.ptr class FixIt(object): - """ - A FixIt represents a transformation to be applied to the source to - "fix-it". The fix-it shouldbe applied by replacing the given source range - with the given value. - """ + """ + A FixIt represents a transformation to be applied to the source to + "fix-it". The fix-it shouldbe applied by replacing the given source range + with the given value. + """ - def __init__(self, range, value): - self.range = range - self.value = value + def __init__(self, range, value): + self.range = range + self.value = value - def __repr__(self): - return "" % (self.range, self.value) + def __repr__(self): + return "" % (self.range, self.value) class TokenGroup(object): - """Helper class to facilitate token management. + """Helper class to facilitate token management. - Tokens are allocated from libclang in chunks. They must be disposed of as a - collective group. + Tokens are allocated from libclang in chunks. They must be disposed of as a + collective group. - One purpose of this class is for instances to represent groups of allocated - tokens. Each token in a group contains a reference back to an instance of - this class. When all tokens from a group are garbage collected, it allows - this class to be garbage collected. When this class is garbage collected, - it calls the libclang destructor which invalidates all tokens in the group. + One purpose of this class is for instances to represent groups of allocated + tokens. Each token in a group contains a reference back to an instance of + this class. When all tokens from a group are garbage collected, it allows + this class to be garbage collected. When this class is garbage collected, + it calls the libclang destructor which invalidates all tokens in the group. - You should not instantiate this class outside of this module. - """ - def __init__(self, tu, memory, count): - self._tu = tu - self._memory = memory - self._count = count + You should not instantiate this class outside of this module. + """ + def __init__(self, tu, memory, count): + self._tu = tu + self._memory = memory + self._count = count - def __del__(self): - conf.lib.clang_disposeTokens(self._tu, self._memory, self._count) + def __del__(self): + conf.lib.clang_disposeTokens(self._tu, self._memory, self._count) - @staticmethod - def get_tokens(tu, extent): - """Helper method to return all tokens in an extent. + @staticmethod + def get_tokens(tu, extent): + """Helper method to return all tokens in an extent. - This functionality is needed multiple places in this module. We define - it here because it seems like a logical place. - """ - tokens_memory = POINTER(Token)() - tokens_count = c_uint() + This functionality is needed multiple places in this module. We define + it here because it seems like a logical place. + """ + tokens_memory = POINTER(Token)() + tokens_count = c_uint() - conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), - byref(tokens_count)) + conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), + byref(tokens_count)) - count = int(tokens_count.value) + count = int(tokens_count.value) - # If we get no tokens, no memory was allocated. Be sure not to return - # anything and potentially call a destructor on nothing. - if count < 1: - return + # If we get no tokens, no memory was allocated. Be sure not to return + # anything and potentially call a destructor on nothing. + if count < 1: + return - tokens_array = cast(tokens_memory, POINTER(Token * count)).contents + tokens_array = cast(tokens_memory, POINTER(Token * count)).contents - token_group = TokenGroup(tu, tokens_memory, tokens_count) + token_group = TokenGroup(tu, tokens_memory, tokens_count) - for i in xrange(0, count): - token = Token() - token.int_data = tokens_array[i].int_data - token.ptr_data = tokens_array[i].ptr_data - token._tu = tu - token._group = token_group + for i in xrange(0, count): + token = Token() + token.int_data = tokens_array[i].int_data + token.ptr_data = tokens_array[i].ptr_data + token._tu = tu + token._group = token_group - yield token + yield token class TokenKind(object): - """Describes a specific type of a Token.""" + """Describes a specific type of a Token.""" - _value_map = {} # int -> TokenKind + _value_map = {} # int -> TokenKind - def __init__(self, value, name): - """Create a new TokenKind instance from a numeric value and a name.""" - self.value = value - self.name = name + def __init__(self, value, name): + """Create a new TokenKind instance from a numeric value and a name.""" + self.value = value + self.name = name - def __repr__(self): - return 'TokenKind.%s' % (self.name,) + def __repr__(self): + return 'TokenKind.%s' % (self.name,) - @staticmethod - def from_value(value): - """Obtain a registered TokenKind instance from its value.""" - result = TokenKind._value_map.get(value, None) + @staticmethod + def from_value(value): + """Obtain a registered TokenKind instance from its value.""" + result = TokenKind._value_map.get(value, None) - if result is None: - raise ValueError('Unknown TokenKind: %d' % value) + if result is None: + raise ValueError('Unknown TokenKind: %d' % value) - return result + return result - @staticmethod - def register(value, name): - """Register a new TokenKind enumeration. + @staticmethod + def register(value, name): + """Register a new TokenKind enumeration. - This should only be called at module load time by code within this - package. - """ - if value in TokenKind._value_map: - raise ValueError('TokenKind already registered: %d' % value) + This should only be called at module load time by code within this + package. + """ + if value in TokenKind._value_map: + raise ValueError('TokenKind already registered: %d' % value) - kind = TokenKind(value, name) - TokenKind._value_map[value] = kind - setattr(TokenKind, name, kind) + kind = TokenKind(value, name) + TokenKind._value_map[value] = kind + setattr(TokenKind, name, kind) ### Cursor Kinds ### class BaseEnumeration(object): - """ - Common base class for named enumerations held in sync with Index.h values. - - Subclasses must define their own _kinds and _name_map members, as: - _kinds = [] - _name_map = None - These values hold the per-subclass instances and value-to-name mappings, - respectively. - - """ - - def __init__(self, value): - if value >= len(self.__class__._kinds): - self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1) - if self.__class__._kinds[value] is not None: - raise ValueError('{0} value {1} already loaded'.format( - str(self.__class__), value)) - self.value = value - self.__class__._kinds[value] = self - self.__class__._name_map = None - - - def from_param(self): - return self.value - - @property - def name(self): - """Get the enumeration name of this cursor kind.""" - if self._name_map is None: - self._name_map = {} - for key, value in self.__class__.__dict__.items(): - if isinstance(value, self.__class__): - self._name_map[value] = key - return self._name_map[self] - - @classmethod - def from_id(cls, id): - if id >= len(cls._kinds) or cls._kinds[id] is None: - raise ValueError('Unknown template argument kind %d' % id) - return cls._kinds[id] - - def __repr__(self): - return '%s.%s' % (self.__class__, self.name,) + """ + Common base class for named enumerations held in sync with Index.h values. + + Subclasses must define their own _kinds and _name_map members, as: + _kinds = [] + _name_map = None + These values hold the per-subclass instances and value-to-name mappings, + respectively. + + """ + + def __init__(self, value): + if value >= len(self.__class__._kinds): + self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1) + if self.__class__._kinds[value] is not None: + raise ValueError('{0} value {1} already loaded'.format( + str(self.__class__), value)) + self.value = value + self.__class__._kinds[value] = self + self.__class__._name_map = None + + + def from_param(self): + return self.value + + @property + def name(self): + """Get the enumeration name of this cursor kind.""" + if self._name_map is None: + self._name_map = {} + for key, value in self.__class__.__dict__.items(): + if isinstance(value, self.__class__): + self._name_map[value] = key + return self._name_map[self] + + @classmethod + def from_id(cls, id): + if id >= len(cls._kinds) or cls._kinds[id] is None: + raise ValueError('Unknown template argument kind %d' % id) + return cls._kinds[id] + + def __repr__(self): + return '%s.%s' % (self.__class__, self.name,) class CursorKind(BaseEnumeration): - """ - A CursorKind describes the kind of entity that a cursor points to. - """ + """ + A CursorKind describes the kind of entity that a cursor points to. + """ - # The required BaseEnumeration declarations. - _kinds = [] - _name_map = None + # The required BaseEnumeration declarations. + _kinds = [] + _name_map = None - @staticmethod - def get_all_kinds(): - """Return all CursorKind enumeration instances.""" - return [x for x in CursorKind._kinds if not x is None] + @staticmethod + def get_all_kinds(): + """Return all CursorKind enumeration instances.""" + return [x for x in CursorKind._kinds if not x is None] - def is_declaration(self): - """Test if this is a declaration kind.""" - return conf.lib.clang_isDeclaration(self) + def is_declaration(self): + """Test if this is a declaration kind.""" + return conf.lib.clang_isDeclaration(self) - def is_reference(self): - """Test if this is a reference kind.""" - return conf.lib.clang_isReference(self) + def is_reference(self): + """Test if this is a reference kind.""" + return conf.lib.clang_isReference(self) - def is_expression(self): - """Test if this is an expression kind.""" - return conf.lib.clang_isExpression(self) + def is_expression(self): + """Test if this is an expression kind.""" + return conf.lib.clang_isExpression(self) - def is_statement(self): - """Test if this is a statement kind.""" - return conf.lib.clang_isStatement(self) + def is_statement(self): + """Test if this is a statement kind.""" + return conf.lib.clang_isStatement(self) - def is_attribute(self): - """Test if this is an attribute kind.""" - return conf.lib.clang_isAttribute(self) + def is_attribute(self): + """Test if this is an attribute kind.""" + return conf.lib.clang_isAttribute(self) - def is_invalid(self): - """Test if this is an invalid kind.""" - return conf.lib.clang_isInvalid(self) + def is_invalid(self): + """Test if this is an invalid kind.""" + return conf.lib.clang_isInvalid(self) - def is_translation_unit(self): - """Test if this is a translation unit kind.""" - return conf.lib.clang_isTranslationUnit(self) + def is_translation_unit(self): + """Test if this is a translation unit kind.""" + return conf.lib.clang_isTranslationUnit(self) - def is_preprocessing(self): - """Test if this is a preprocessing kind.""" - return conf.lib.clang_isPreprocessing(self) + def is_preprocessing(self): + """Test if this is a preprocessing kind.""" + return conf.lib.clang_isPreprocessing(self) - def is_unexposed(self): - """Test if this is an unexposed kind.""" - return conf.lib.clang_isUnexposed(self) + def is_unexposed(self): + """Test if this is an unexposed kind.""" + return conf.lib.clang_isUnexposed(self) - def __repr__(self): - return 'CursorKind.%s' % (self.name,) + def __repr__(self): + return 'CursorKind.%s' % (self.name,) ### # Declaration Kinds @@ -802,7 +812,7 @@ def __repr__(self): # A C++ template type parameter CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) -# A C++ non-type template parameter. +# A C++ non-type template paramater. CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) # A C++ template template parameter. @@ -1069,10 +1079,10 @@ def __repr__(self): # # \code # void abssort(float *x, unsigned N) { -# std::sort(x, x + N, -# [](float a, float b) { -# return std::abs(a) < std::abs(b); -# }); +# std::sort(x, x + N, +# [](float a, float b) { +# return std::abs(a) < std::abs(b); +# }); # } # \endcode CursorKind.LAMBDA_EXPR = CursorKind(144) @@ -1083,15 +1093,15 @@ def __repr__(self): # Represents the "self" expression in a ObjC method. CursorKind.OBJ_SELF_EXPR = CursorKind(146) -# OpenMP 4.0 [2.4, Array Section]. -CursorKind.OMP_ARRAY_SECTION_EXPR = CursorKind(147) - -# Represents an @available(...) check. -CursorKind.OBJC_AVAILABILITY_CHECK_EXPR = CursorKind(148) - +CursorKind.OMP_ARRAY_SECTION_EXPR = CursorKind(147) # A statement whose specific kind is not exposed via this interface. # +CursorKind.OBJC_AVAILABILITY_CHECK_EXPR = CursorKind(148) +# Unexposed statements have the same operations as any other kind of statement; +# one can extract their location information, spelling, children, etc. However, +# the specific kind of the statement is not reported. +# # Unexposed statements have the same operations as any other kind of statement; # one can extract their location information, spelling, children, etc. However, # the specific kind of the statement is not reported. @@ -1190,16 +1200,16 @@ def __repr__(self): # Adaptor class for mixing declarations with statements and expressions. CursorKind.DECL_STMT = CursorKind(231) -# OpenMP parallel directive. +### CursorKind.OMP_PARALLEL_DIRECTIVE = CursorKind(232) +# Other Kinds -# OpenMP SIMD directive. CursorKind.OMP_SIMD_DIRECTIVE = CursorKind(233) - -# OpenMP for directive. +# Cursor that represents the translation unit itself. +# CursorKind.OMP_FOR_DIRECTIVE = CursorKind(234) - -# OpenMP sections directive. +# The translation unit cursor exists primarily to act as the root cursor for +# traversing the contents of a translation unit. CursorKind.OMP_SECTIONS_DIRECTIVE = CursorKind(235) # OpenMP section directive. @@ -1372,14 +1382,14 @@ def __repr__(self): ### Template Argument Kinds ### class TemplateArgumentKind(BaseEnumeration): - """ - A TemplateArgumentKind describes the kind of entity that a template argument - represents. - """ + """ + A TemplateArgumentKind describes the kind of entity that a template argument + represents. + """ - # The required BaseEnumeration declarations. - _kinds = [] - _name_map = None + # The required BaseEnumeration declarations. + _kinds = [] + _name_map = None TemplateArgumentKind.NULL = TemplateArgumentKind(0) TemplateArgumentKind.TYPE = TemplateArgumentKind(1) @@ -1389,17 +1399,17 @@ class TemplateArgumentKind(BaseEnumeration): ### Exception Specification Kinds ### class ExceptionSpecificationKind(BaseEnumeration): - """ - An ExceptionSpecificationKind describes the kind of exception specification - that a function has. - """ + """ + An ExceptionSpecificationKind describes the kind of exception specification + that a function has. + """ - # The required BaseEnumeration declarations. - _kinds = [] - _name_map = None + # The required BaseEnumeration declarations. + _kinds = [] + _name_map = None - def __repr__(self): - return 'ExceptionSpecificationKind.{}'.format(self.name) + def __repr__(self): + return 'ExceptionSpecificationKind.{}'.format(self.name) ExceptionSpecificationKind.NONE = ExceptionSpecificationKind(0) ExceptionSpecificationKind.DYNAMIC_NONE = ExceptionSpecificationKind(1) @@ -1414,529 +1424,529 @@ def __repr__(self): ### Cursors ### class Cursor(Structure): - """ - The Cursor class represents a reference to an element within the AST. It - acts as a kind of iterator. - """ - _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] - - @staticmethod - def from_location(tu, location): - # We store a reference to the TU in the instance so the TU won't get - # collected before the cursor. - cursor = conf.lib.clang_getCursor(tu, location) - cursor._tu = tu - - return cursor - - def __eq__(self, other): - return conf.lib.clang_equalCursors(self, other) - - def __ne__(self, other): - return not self.__eq__(other) - - def is_definition(self): - """ - Returns true if the declaration pointed at by the cursor is also a - definition of that entity. - """ - return conf.lib.clang_isCursorDefinition(self) - - def is_const_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared 'const'. - """ - return conf.lib.clang_CXXMethod_isConst(self) - - def is_converting_constructor(self): - """Returns True if the cursor refers to a C++ converting constructor. - """ - return conf.lib.clang_CXXConstructor_isConvertingConstructor(self) - - def is_copy_constructor(self): - """Returns True if the cursor refers to a C++ copy constructor. - """ - return conf.lib.clang_CXXConstructor_isCopyConstructor(self) - - def is_default_constructor(self): - """Returns True if the cursor refers to a C++ default constructor. - """ - return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) - - def is_move_constructor(self): - """Returns True if the cursor refers to a C++ move constructor. - """ - return conf.lib.clang_CXXConstructor_isMoveConstructor(self) - - def is_default_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared '= default'. - """ - return conf.lib.clang_CXXMethod_isDefaulted(self) - - def is_mutable_field(self): - """Returns True if the cursor refers to a C++ field that is declared - 'mutable'. - """ - return conf.lib.clang_CXXField_isMutable(self) - - def is_pure_virtual_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared pure virtual. - """ - return conf.lib.clang_CXXMethod_isPureVirtual(self) - - def is_static_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared 'static'. - """ - return conf.lib.clang_CXXMethod_isStatic(self) - - def is_virtual_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared 'virtual'. - """ - return conf.lib.clang_CXXMethod_isVirtual(self) - - def get_definition(self): - """ - If the cursor is a reference to a declaration or a declaration of - some entity, return a cursor that points to the definition of that - entity. - """ - # TODO: Should probably check that this is either a reference or - # declaration prior to issuing the lookup. - return conf.lib.clang_getCursorDefinition(self) - - def get_usr(self): - """Return the Unified Symbol Resultion (USR) for the entity referenced - by the given cursor (or None). - - A Unified Symbol Resolution (USR) is a string that identifies a - particular entity (function, class, variable, etc.) within a - program. USRs can be compared across translation units to determine, - e.g., when references in one translation refer to an entity defined in - another translation unit.""" - return conf.lib.clang_getCursorUSR(self) - - @property - def kind(self): - """Return the kind of this cursor.""" - return CursorKind.from_id(self._kind_id) - - @property - def spelling(self): - """Return the spelling of the entity pointed at by the cursor.""" - if not hasattr(self, '_spelling'): - self._spelling = conf.lib.clang_getCursorSpelling(self) - - return self._spelling - - @property - def displayname(self): - """ - Return the display name for the entity referenced by this cursor. - - The display name contains extra information that helps identify the - cursor, such as the parameters of a function or template or the - arguments of a class template specialization. - """ - if not hasattr(self, '_displayname'): - self._displayname = conf.lib.clang_getCursorDisplayName(self) - - return self._displayname - - @property - def mangled_name(self): - """Return the mangled name for the entity referenced by this cursor.""" - if not hasattr(self, '_mangled_name'): - self._mangled_name = conf.lib.clang_Cursor_getMangling(self) - - return self._mangled_name - - @property - def location(self): - """ - Return the source location (the starting character) of the entity - pointed at by the cursor. - """ - if not hasattr(self, '_loc'): - self._loc = conf.lib.clang_getCursorLocation(self) - - return self._loc - - @property - def linkage(self): - """Return the linkage of this cursor.""" - if not hasattr(self, '_linkage'): - self._linkage = conf.lib.clang_getCursorLinkage(self) - - return LinkageKind.from_id(self._linkage) - - @property - def extent(self): - """ - Return the source range (the range of text) occupied by the entity - pointed at by the cursor. - """ - if not hasattr(self, '_extent'): - self._extent = conf.lib.clang_getCursorExtent(self) - - return self._extent - - @property - def storage_class(self): - """ - Retrieves the storage class (if any) of the entity pointed at by the - cursor. - """ - if not hasattr(self, '_storage_class'): - self._storage_class = conf.lib.clang_Cursor_getStorageClass(self) - - return StorageClass.from_id(self._storage_class) - - @property - def availability(self): - """ - Retrieves the availability of the entity pointed at by the cursor. - """ - if not hasattr(self, '_availability'): - self._availability = conf.lib.clang_getCursorAvailability(self) - - return AvailabilityKind.from_id(self._availability) - - @property - def access_specifier(self): - """ - Retrieves the access specifier (if any) of the entity pointed at by the - cursor. - """ - if not hasattr(self, '_access_specifier'): - self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) - - return AccessSpecifier.from_id(self._access_specifier) - - @property - def type(self): - """ - Retrieve the Type (if any) of the entity pointed at by the cursor. - """ - if not hasattr(self, '_type'): - self._type = conf.lib.clang_getCursorType(self) - - return self._type - - @property - def canonical(self): - """Return the canonical Cursor corresponding to this Cursor. - - The canonical cursor is the cursor which is representative for the - underlying entity. For example, if you have multiple forward - declarations for the same class, the canonical cursor for the forward - declarations will be identical. - """ - if not hasattr(self, '_canonical'): - self._canonical = conf.lib.clang_getCanonicalCursor(self) - - return self._canonical - - @property - def result_type(self): - """Retrieve the Type of the result for this Cursor.""" - if not hasattr(self, '_result_type'): - self._result_type = conf.lib.clang_getResultType(self.type) - - return self._result_type - - @property - def underlying_typedef_type(self): - """Return the underlying type of a typedef declaration. - - Returns a Type for the typedef this cursor is a declaration for. If - the current cursor is not a typedef, this raises. - """ - if not hasattr(self, '_underlying_type'): - assert self.kind.is_declaration() - self._underlying_type = \ - conf.lib.clang_getTypedefDeclUnderlyingType(self) - - return self._underlying_type - - @property - def enum_type(self): - """Return the integer type of an enum declaration. - - Returns a Type corresponding to an integer. If the cursor is not for an - enum, this raises. - """ - if not hasattr(self, '_enum_type'): - assert self.kind == CursorKind.ENUM_DECL - self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) - - return self._enum_type - - @property - def enum_value(self): - """Return the value of an enum constant.""" - if not hasattr(self, '_enum_value'): - assert self.kind == CursorKind.ENUM_CONSTANT_DECL - # Figure out the underlying type of the enum to know if it - # is a signed or unsigned quantity. - underlying_type = self.type - if underlying_type.kind == TypeKind.ENUM: - underlying_type = underlying_type.get_declaration().enum_type - if underlying_type.kind in (TypeKind.CHAR_U, - TypeKind.UCHAR, - TypeKind.CHAR16, - TypeKind.CHAR32, - TypeKind.USHORT, - TypeKind.UINT, - TypeKind.ULONG, - TypeKind.ULONGLONG, - TypeKind.UINT128): - self._enum_value = \ - conf.lib.clang_getEnumConstantDeclUnsignedValue(self) - else: - self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) - return self._enum_value - - @property - def objc_type_encoding(self): - """Return the Objective-C type encoding as a str.""" - if not hasattr(self, '_objc_type_encoding'): - self._objc_type_encoding = \ - conf.lib.clang_getDeclObjCTypeEncoding(self) - - return self._objc_type_encoding - - @property - def hash(self): - """Returns a hash of the cursor as an int.""" - if not hasattr(self, '_hash'): - self._hash = conf.lib.clang_hashCursor(self) - - return self._hash - - def __hash__(self): - return self.hash - - @property - def semantic_parent(self): - """Return the semantic parent for this cursor.""" - if not hasattr(self, '_semantic_parent'): - self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) - - return self._semantic_parent - - @property - def lexical_parent(self): - """Return the lexical parent for this cursor.""" - if not hasattr(self, '_lexical_parent'): - self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) - - return self._lexical_parent - - @property - def translation_unit(self): - """Returns the TranslationUnit to which this Cursor belongs.""" - # If this triggers an AttributeError, the instance was not properly - # created. - return self._tu - - @property - def referenced(self): - """ - For a cursor that is a reference, returns a cursor - representing the entity that it references. - """ - if not hasattr(self, '_referenced'): - self._referenced = conf.lib.clang_getCursorReferenced(self) - - return self._referenced - - @property - def brief_comment(self): - """Returns the brief comment text associated with that Cursor""" - return conf.lib.clang_Cursor_getBriefCommentText(self) - - @property - def raw_comment(self): - """Returns the raw comment text associated with that Cursor""" - return conf.lib.clang_Cursor_getRawCommentText(self) - - def get_arguments(self): - """Return an iterator for accessing the arguments of this cursor.""" - num_args = conf.lib.clang_Cursor_getNumArguments(self) - for i in range(0, num_args): - yield conf.lib.clang_Cursor_getArgument(self, i) - - def get_num_template_arguments(self): - """Returns the number of template args associated with this cursor.""" - return conf.lib.clang_Cursor_getNumTemplateArguments(self) - - def get_template_argument_kind(self, num): - """Returns the TemplateArgumentKind for the indicated template - argument.""" - return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num) - - def get_template_argument_type(self, num): - """Returns the CXType for the indicated template argument.""" - return conf.lib.clang_Cursor_getTemplateArgumentType(self, num) - - def get_template_argument_value(self, num): - """Returns the value of the indicated arg as a signed 64b integer.""" - return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num) - - def get_template_argument_unsigned_value(self, num): - """Returns the value of the indicated arg as an unsigned 64b integer.""" - return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num) - - def get_children(self): - """Return an iterator for accessing the children of this cursor.""" - - # FIXME: Expose iteration from CIndex, PR6125. - def visitor(child, parent, children): - # FIXME: Document this assertion in API. - # FIXME: There should just be an isNull method. - assert child != conf.lib.clang_getNullCursor() - - # Create reference to TU so it isn't GC'd before Cursor. - child._tu = self._tu - children.append(child) - return 1 # continue - children = [] - conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), - children) - return iter(children) - - def walk_preorder(self): - """Depth-first preorder walk over the cursor and its descendants. - - Yields cursors. - """ - yield self - for child in self.get_children(): - for descendant in child.walk_preorder(): - yield descendant - - def get_tokens(self): - """Obtain Token instances formulating that compose this Cursor. - - This is a generator for Token instances. It returns all tokens which - occupy the extent this cursor occupies. - """ - return TokenGroup.get_tokens(self._tu, self.extent) - - def get_field_offsetof(self): - """Returns the offsetof the FIELD_DECL pointed by this Cursor.""" - return conf.lib.clang_Cursor_getOffsetOfField(self) - - def is_anonymous(self): - """ - Check if the record is anonymous. - """ - if self.kind == CursorKind.FIELD_DECL: - return self.type.get_declaration().is_anonymous() - return conf.lib.clang_Cursor_isAnonymous(self) - - def is_bitfield(self): - """ - Check if the field is a bitfield. - """ - return conf.lib.clang_Cursor_isBitField(self) - - def get_bitfield_width(self): - """ - Retrieve the width of a bitfield. - """ - return conf.lib.clang_getFieldDeclBitWidth(self) - - @property - def specialized_cursor_template(self): - """ - Retrieve the specialized cursor template. - """ - return conf.lib.clang_getSpecializedCursorTemplate(self) - - @property - def template_cursor_kind(self): - """ - Retrieve the template cursor kind. - """ - return conf.lib.clang_getTemplateCursorKind(self) - - @staticmethod - def from_result(res, fn, args): - assert isinstance(res, Cursor) - # FIXME: There should just be an isNull method. - if res == conf.lib.clang_getNullCursor(): - return None - - # Store a reference to the TU in the Python object so it won't get GC'd - # before the Cursor. - tu = None - for arg in args: - if isinstance(arg, TranslationUnit): - tu = arg - break - - if hasattr(arg, 'translation_unit'): - tu = arg.translation_unit - break - - assert tu is not None - - res._tu = tu - return res - - @staticmethod - def from_cursor_result(res, fn, args): - assert isinstance(res, Cursor) - if res == conf.lib.clang_getNullCursor(): - return None - - res._tu = args[0]._tu - return res + """ + The Cursor class represents a reference to an element within the AST. It + acts as a kind of iterator. + """ + _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] + + @staticmethod + def from_location(tu, location): + # We store a reference to the TU in the instance so the TU won't get + # collected before the cursor. + cursor = conf.lib.clang_getCursor(tu, location) + cursor._tu = tu + + return cursor + + def __eq__(self, other): + return conf.lib.clang_equalCursors(self, other) + + def __ne__(self, other): + return not self.__eq__(other) + + def is_definition(self): + """ + Returns true if the declaration pointed at by the cursor is also a + definition of that entity. + """ + return conf.lib.clang_isCursorDefinition(self) + + def is_const_method(self): + """Returns True if the cursor refers to a C++ member function or member + function template that is declared 'const'. + """ + return conf.lib.clang_CXXMethod_isConst(self) + + def is_converting_constructor(self): + """Returns True if the cursor refers to a C++ converting constructor. + """ + return conf.lib.clang_CXXConstructor_isConvertingConstructor(self) + + def is_copy_constructor(self): + """Returns True if the cursor refers to a C++ copy constructor. + """ + return conf.lib.clang_CXXConstructor_isCopyConstructor(self) + + def is_default_constructor(self): + """Returns True if the cursor refers to a C++ default constructor. + """ + return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) + + def is_move_constructor(self): + """Returns True if the cursor refers to a C++ move constructor. + """ + return conf.lib.clang_CXXConstructor_isMoveConstructor(self) + + def is_default_method(self): + """Returns True if the cursor refers to a C++ member function or member + function template that is declared '= default'. + """ + return conf.lib.clang_CXXMethod_isDefaulted(self) + + def is_mutable_field(self): + """Returns True if the cursor refers to a C++ field that is declared + 'mutable'. + """ + return conf.lib.clang_CXXField_isMutable(self) + + def is_pure_virtual_method(self): + """Returns True if the cursor refers to a C++ member function or member + function template that is declared pure virtual. + """ + return conf.lib.clang_CXXMethod_isPureVirtual(self) + + def is_static_method(self): + """Returns True if the cursor refers to a C++ member function or member + function template that is declared 'static'. + """ + return conf.lib.clang_CXXMethod_isStatic(self) + + def is_virtual_method(self): + """Returns True if the cursor refers to a C++ member function or member + function template that is declared 'virtual'. + """ + return conf.lib.clang_CXXMethod_isVirtual(self) + + def get_definition(self): + """ + If the cursor is a reference to a declaration or a declaration of + some entity, return a cursor that points to the definition of that + entity. + """ + # TODO: Should probably check that this is either a reference or + # declaration prior to issuing the lookup. + return conf.lib.clang_getCursorDefinition(self) + + def get_usr(self): + """Return the Unified Symbol Resolution (USR) for the entity referenced + by the given cursor (or None). + + A Unified Symbol Resolution (USR) is a string that identifies a + particular entity (function, class, variable, etc.) within a + program. USRs can be compared across translation units to determine, + e.g., when references in one translation refer to an entity defined in + another translation unit.""" + return conf.lib.clang_getCursorUSR(self) + + @property + def kind(self): + """Return the kind of this cursor.""" + return CursorKind.from_id(self._kind_id) + + @property + def spelling(self): + """Return the spelling of the entity pointed at by the cursor.""" + if not hasattr(self, '_spelling'): + self._spelling = conf.lib.clang_getCursorSpelling(self) + + return self._spelling + + @property + def displayname(self): + """ + Return the display name for the entity referenced by this cursor. + + The display name contains extra information that helps identify the + cursor, such as the parameters of a function or template or the + arguments of a class template specialization. + """ + if not hasattr(self, '_displayname'): + self._displayname = conf.lib.clang_getCursorDisplayName(self) + + return self._displayname + + @property + def mangled_name(self): + """Return the mangled name for the entity referenced by this cursor.""" + if not hasattr(self, '_mangled_name'): + self._mangled_name = conf.lib.clang_Cursor_getMangling(self) + + return self._mangled_name + + @property + def location(self): + """ + Return the source location (the starting character) of the entity + pointed at by the cursor. + """ + if not hasattr(self, '_loc'): + self._loc = conf.lib.clang_getCursorLocation(self) + + return self._loc + + @property + def linkage(self): + """Return the linkage of this cursor.""" + if not hasattr(self, '_linkage'): + self._linkage = conf.lib.clang_getCursorLinkage(self) + + return LinkageKind.from_id(self._linkage) + + @property + def extent(self): + """ + Return the source range (the range of text) occupied by the entity + pointed at by the cursor. + """ + if not hasattr(self, '_extent'): + self._extent = conf.lib.clang_getCursorExtent(self) + + return self._extent + + @property + def storage_class(self): + """ + Retrieves the storage class (if any) of the entity pointed at by the + cursor. + """ + if not hasattr(self, '_storage_class'): + self._storage_class = conf.lib.clang_Cursor_getStorageClass(self) + + return StorageClass.from_id(self._storage_class) + + @property + def availability(self): + """ + Retrieves the availability of the entity pointed at by the cursor. + """ + if not hasattr(self, '_availability'): + self._availability = conf.lib.clang_getCursorAvailability(self) + + return AvailabilityKind.from_id(self._availability) + + @property + def access_specifier(self): + """ + Retrieves the access specifier (if any) of the entity pointed at by the + cursor. + """ + if not hasattr(self, '_access_specifier'): + self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) + + return AccessSpecifier.from_id(self._access_specifier) + + @property + def type(self): + """ + Retrieve the Type (if any) of the entity pointed at by the cursor. + """ + if not hasattr(self, '_type'): + self._type = conf.lib.clang_getCursorType(self) + + return self._type + + @property + def canonical(self): + """Return the canonical Cursor corresponding to this Cursor. + + The canonical cursor is the cursor which is representative for the + underlying entity. For example, if you have multiple forward + declarations for the same class, the canonical cursor for the forward + declarations will be identical. + """ + if not hasattr(self, '_canonical'): + self._canonical = conf.lib.clang_getCanonicalCursor(self) + + return self._canonical + + @property + def result_type(self): + """Retrieve the Type of the result for this Cursor.""" + if not hasattr(self, '_result_type'): + self._result_type = conf.lib.clang_getResultType(self.type) + + return self._result_type + + @property + def underlying_typedef_type(self): + """Return the underlying type of a typedef declaration. + + Returns a Type for the typedef this cursor is a declaration for. If + the current cursor is not a typedef, this raises. + """ + if not hasattr(self, '_underlying_type'): + assert self.kind.is_declaration() + self._underlying_type = \ + conf.lib.clang_getTypedefDeclUnderlyingType(self) + + return self._underlying_type + + @property + def enum_type(self): + """Return the integer type of an enum declaration. + + Returns a Type corresponding to an integer. If the cursor is not for an + enum, this raises. + """ + if not hasattr(self, '_enum_type'): + assert self.kind == CursorKind.ENUM_DECL + self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) + + return self._enum_type + + @property + def enum_value(self): + """Return the value of an enum constant.""" + if not hasattr(self, '_enum_value'): + assert self.kind == CursorKind.ENUM_CONSTANT_DECL + # Figure out the underlying type of the enum to know if it + # is a signed or unsigned quantity. + underlying_type = self.type + if underlying_type.kind == TypeKind.ENUM: + underlying_type = underlying_type.get_declaration().enum_type + if underlying_type.kind in (TypeKind.CHAR_U, + TypeKind.UCHAR, + TypeKind.CHAR16, + TypeKind.CHAR32, + TypeKind.USHORT, + TypeKind.UINT, + TypeKind.ULONG, + TypeKind.ULONGLONG, + TypeKind.UINT128): + self._enum_value = \ + conf.lib.clang_getEnumConstantDeclUnsignedValue(self) + else: + self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) + return self._enum_value + + @property + def objc_type_encoding(self): + """Return the Objective-C type encoding as a str.""" + if not hasattr(self, '_objc_type_encoding'): + self._objc_type_encoding = \ + conf.lib.clang_getDeclObjCTypeEncoding(self) + + return self._objc_type_encoding + + @property + def hash(self): + """Returns a hash of the cursor as an int.""" + if not hasattr(self, '_hash'): + self._hash = conf.lib.clang_hashCursor(self) + + return self._hash + + def __hash__(self): + return self.hash + + @property + def semantic_parent(self): + """Return the semantic parent for this cursor.""" + if not hasattr(self, '_semantic_parent'): + self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) + + return self._semantic_parent + + @property + def lexical_parent(self): + """Return the lexical parent for this cursor.""" + if not hasattr(self, '_lexical_parent'): + self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) + + return self._lexical_parent + + @property + def translation_unit(self): + """Returns the TranslationUnit to which this Cursor belongs.""" + # If this triggers an AttributeError, the instance was not properly + # created. + return self._tu + + @property + def referenced(self): + """ + For a cursor that is a reference, returns a cursor + representing the entity that it references. + """ + if not hasattr(self, '_referenced'): + self._referenced = conf.lib.clang_getCursorReferenced(self) + + return self._referenced + + @property + def brief_comment(self): + """Returns the brief comment text associated with that Cursor""" + return conf.lib.clang_Cursor_getBriefCommentText(self) + + @property + def raw_comment(self): + """Returns the raw comment text associated with that Cursor""" + return conf.lib.clang_Cursor_getRawCommentText(self) + + def get_arguments(self): + """Return an iterator for accessing the arguments of this cursor.""" + num_args = conf.lib.clang_Cursor_getNumArguments(self) + for i in range(0, num_args): + yield conf.lib.clang_Cursor_getArgument(self, i) + + def get_num_template_arguments(self): + """Returns the number of template args associated with this cursor.""" + return conf.lib.clang_Cursor_getNumTemplateArguments(self) + + def get_template_argument_kind(self, num): + """Returns the TemplateArgumentKind for the indicated template + argument.""" + return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num) + + def get_template_argument_type(self, num): + """Returns the CXType for the indicated template argument.""" + return conf.lib.clang_Cursor_getTemplateArgumentType(self, num) + + def get_template_argument_value(self, num): + """Returns the value of the indicated arg as a signed 64b integer.""" + return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num) + + def get_template_argument_unsigned_value(self, num): + """Returns the value of the indicated arg as an unsigned 64b integer.""" + return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num) + + def get_children(self): + """Return an iterator for accessing the children of this cursor.""" + + # FIXME: Expose iteration from CIndex, PR6125. + def visitor(child, parent, children): + # FIXME: Document this assertion in API. + # FIXME: There should just be an isNull method. + assert child != conf.lib.clang_getNullCursor() + + # Create reference to TU so it isn't GC'd before Cursor. + child._tu = self._tu + children.append(child) + return 1 # continue + children = [] + conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), + children) + return iter(children) + + def walk_preorder(self): + """Depth-first preorder walk over the cursor and its descendants. + + Yields cursors. + """ + yield self + for child in self.get_children(): + for descendant in child.walk_preorder(): + yield descendant + + def get_tokens(self): + """Obtain Token instances formulating that compose this Cursor. + + This is a generator for Token instances. It returns all tokens which + occupy the extent this cursor occupies. + """ + return TokenGroup.get_tokens(self._tu, self.extent) + + def get_field_offsetof(self): + """Returns the offsetof the FIELD_DECL pointed by this Cursor.""" + return conf.lib.clang_Cursor_getOffsetOfField(self) + + def is_anonymous(self): + """ + Check if the record is anonymous. + """ + if self.kind == CursorKind.FIELD_DECL: + return self.type.get_declaration().is_anonymous() + return conf.lib.clang_Cursor_isAnonymous(self) + + def is_bitfield(self): + """ + Check if the field is a bitfield. + """ + return conf.lib.clang_Cursor_isBitField(self) + + def get_bitfield_width(self): + """ + Retrieve the width of a bitfield. + """ + return conf.lib.clang_getFieldDeclBitWidth(self) + + @property + def specialized_cursor_template(self): + """ + Retrieve the specialized cursor template. + """ + return conf.lib.clang_getSpecializedCursorTemplate(self) + + @property + def template_cursor_kind(self): + """ + Retrieve the template cursor kind. + """ + return conf.lib.clang_getTemplateCursorKind(self) + + @staticmethod + def from_result(res, fn, args): + assert isinstance(res, Cursor) + # FIXME: There should just be an isNull method. + if res == conf.lib.clang_getNullCursor(): + return None + + # Store a reference to the TU in the Python object so it won't get GC'd + # before the Cursor. + tu = None + for arg in args: + if isinstance(arg, TranslationUnit): + tu = arg + break + + if hasattr(arg, 'translation_unit'): + tu = arg.translation_unit + break + + assert tu is not None + + res._tu = tu + return res + + @staticmethod + def from_cursor_result(res, fn, args): + assert isinstance(res, Cursor) + if res == conf.lib.clang_getNullCursor(): + return None + + res._tu = args[0]._tu + return res class StorageClass(object): - """ - Describes the storage class of a declaration - """ - - # The unique kind objects, index by id. - _kinds = [] - _name_map = None - - def __init__(self, value): - if value >= len(StorageClass._kinds): - StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1) - if StorageClass._kinds[value] is not None: - raise ValueError('StorageClass already loaded') - self.value = value - StorageClass._kinds[value] = self - StorageClass._name_map = None - - def from_param(self): - return self.value - - @property - def name(self): - """Get the enumeration name of this storage class.""" - if self._name_map is None: - self._name_map = {} - for key,value in StorageClass.__dict__.items(): - if isinstance(value,StorageClass): - self._name_map[value] = key - return self._name_map[self] - - @staticmethod - def from_id(id): - if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]: - raise ValueError('Unknown storage class %d' % id) - return StorageClass._kinds[id] - - def __repr__(self): - return 'StorageClass.%s' % (self.name,) + """ + Describes the storage class of a declaration + """ + + # The unique kind objects, index by id. + _kinds = [] + _name_map = None + + def __init__(self, value): + if value >= len(StorageClass._kinds): + StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1) + if StorageClass._kinds[value] is not None: + raise ValueError('StorageClass already loaded') + self.value = value + StorageClass._kinds[value] = self + StorageClass._name_map = None + + def from_param(self): + return self.value + + @property + def name(self): + """Get the enumeration name of this storage class.""" + if self._name_map is None: + self._name_map = {} + for key,value in StorageClass.__dict__.items(): + if isinstance(value,StorageClass): + self._name_map[value] = key + return self._name_map[self] + + @staticmethod + def from_id(id): + if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]: + raise ValueError('Unknown storage class %d' % id) + return StorageClass._kinds[id] + + def __repr__(self): + return 'StorageClass.%s' % (self.name,) StorageClass.INVALID = StorageClass(0) StorageClass.NONE = StorageClass(1) @@ -1950,16 +1960,16 @@ def __repr__(self): ### Availability Kinds ### class AvailabilityKind(BaseEnumeration): - """ - Describes the availability of an entity. - """ + """ + Describes the availability of an entity. + """ - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None + # The unique kind objects, indexed by id. + _kinds = [] + _name_map = None - def __repr__(self): - return 'AvailabilityKind.%s' % (self.name,) + def __repr__(self): + return 'AvailabilityKind.%s' % (self.name,) AvailabilityKind.AVAILABLE = AvailabilityKind(0) AvailabilityKind.DEPRECATED = AvailabilityKind(1) @@ -1969,19 +1979,19 @@ def __repr__(self): ### C++ access specifiers ### class AccessSpecifier(BaseEnumeration): - """ - Describes the access of a C++ class member - """ + """ + Describes the access of a C++ class member + """ - # The unique kind objects, index by id. - _kinds = [] - _name_map = None + # The unique kind objects, index by id. + _kinds = [] + _name_map = None - def from_param(self): - return self.value + def from_param(self): + return self.value - def __repr__(self): - return 'AccessSpecifier.%s' % (self.name,) + def __repr__(self): + return 'AccessSpecifier.%s' % (self.name,) AccessSpecifier.INVALID = AccessSpecifier(0) AccessSpecifier.PUBLIC = AccessSpecifier(1) @@ -1992,21 +2002,21 @@ def __repr__(self): ### Type Kinds ### class TypeKind(BaseEnumeration): - """ - Describes the kind of type. - """ + """ + Describes the kind of type. + """ - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None + # The unique kind objects, indexed by id. + _kinds = [] + _name_map = None - @property - def spelling(self): - """Retrieve the spelling of this TypeKind.""" - return conf.lib.clang_getTypeKindSpelling(self.value) + @property + def spelling(self): + """Retrieve the spelling of this TypeKind.""" + return conf.lib.clang_getTypeKindSpelling(self.value) - def __repr__(self): - return 'TypeKind.%s' % (self.name,) + def __repr__(self): + return 'TypeKind.%s' % (self.name,) TypeKind.INVALID = TypeKind(0) TypeKind.UNEXPOSED = TypeKind(1) @@ -2103,34 +2113,34 @@ def __repr__(self): TypeKind.OCLRESERVEID = TypeKind(160) class RefQualifierKind(BaseEnumeration): - """Describes a specific ref-qualifier of a type.""" + """Describes a specific ref-qualifier of a type.""" - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None + # The unique kind objects, indexed by id. + _kinds = [] + _name_map = None - def from_param(self): - return self.value + def from_param(self): + return self.value - def __repr__(self): - return 'RefQualifierKind.%s' % (self.name,) + def __repr__(self): + return 'RefQualifierKind.%s' % (self.name,) RefQualifierKind.NONE = RefQualifierKind(0) RefQualifierKind.LVALUE = RefQualifierKind(1) RefQualifierKind.RVALUE = RefQualifierKind(2) class LinkageKind(BaseEnumeration): - """Describes the kind of linkage of a cursor.""" + """Describes the kind of linkage of a cursor.""" - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None + # The unique kind objects, indexed by id. + _kinds = [] + _name_map = None - def from_param(self): - return self.value + def from_param(self): + return self.value - def __repr__(self): - return 'LinkageKind.%s' % (self.name,) + def __repr__(self): + return 'LinkageKind.%s' % (self.name,) LinkageKind.INVALID = LinkageKind(0) LinkageKind.NO_LINKAGE = LinkageKind(1) @@ -2139,276 +2149,276 @@ def __repr__(self): LinkageKind.EXTERNAL = LinkageKind(4) class TLSKind(BaseEnumeration): - """Describes the kind of thread-local storage (TLS) of a cursor.""" + """Describes the kind of thread-local storage (TLS) of a cursor.""" - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None + # The unique kind objects, indexed by id. + _kinds = [] + _name_map = None - def from_param(self): - return self.value + def from_param(self): + return self.value - def __repr__(self): - return 'TLSKind.%s' % (self.name,) + def __repr__(self): + return 'TLSKind.%s' % (self.name,) TLSKind.NONE = TLSKind(0) TLSKind.DYNAMIC = TLSKind(1) TLSKind.STATIC = TLSKind(2) class Type(Structure): - """ - The type of an element in the abstract syntax tree. - """ - _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] + """ + The type of an element in the abstract syntax tree. + """ + _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] - @property - def kind(self): - """Return the kind of this type.""" - return TypeKind.from_id(self._kind_id) + @property + def kind(self): + """Return the kind of this type.""" + return TypeKind.from_id(self._kind_id) - def get_num_template_arguments(self): - return conf.lib.clang_Type_getNumTemplateArguments(self) - - def get_template_argument_type(self, num): - """Returns the CXType for the indicated template argument.""" - return conf.lib.clang_Type_getTemplateArgumentAsType(self, num) - - def argument_types(self): - """Retrieve a container for the non-variadic arguments for this type. - - The returned object is iterable and indexable. Each item in the - container is a Type instance. - """ - class ArgumentsIterator(collections.Sequence): - def __init__(self, parent): - self.parent = parent - self.length = None - - def __len__(self): - if self.length is None: - self.length = conf.lib.clang_getNumArgTypes(self.parent) - - return self.length - - def __getitem__(self, key): - # FIXME Support slice objects. - if not isinstance(key, int): - raise TypeError("Must supply a non-negative int.") - - if key < 0: - raise IndexError("Only non-negative indexes are accepted.") - - if key >= len(self): - raise IndexError("Index greater than container length: " - "%d > %d" % ( key, len(self) )) + def get_num_template_arguments(self): + return conf.lib.clang_Type_getNumTemplateArguments(self) + + def get_template_argument_type(self, num): + """Returns the CXType for the indicated template argument.""" + return conf.lib.clang_Type_getTemplateArgumentAsType(self, num) + + def argument_types(self): + """Retrieve a container for the non-variadic arguments for this type. + + The returned object is iterable and indexable. Each item in the + container is a Type instance. + """ + class ArgumentsIterator(collections.Sequence): + def __init__(self, parent): + self.parent = parent + self.length = None + + def __len__(self): + if self.length is None: + self.length = conf.lib.clang_getNumArgTypes(self.parent) + + return self.length + + def __getitem__(self, key): + # FIXME Support slice objects. + if not isinstance(key, int): + raise TypeError("Must supply a non-negative int.") + + if key < 0: + raise IndexError("Only non-negative indexes are accepted.") + + if key >= len(self): + raise IndexError("Index greater than container length: " + "%d > %d" % ( key, len(self) )) - result = conf.lib.clang_getArgType(self.parent, key) - if result.kind == TypeKind.INVALID: - raise IndexError("Argument could not be retrieved.") + result = conf.lib.clang_getArgType(self.parent, key) + if result.kind == TypeKind.INVALID: + raise IndexError("Argument could not be retrieved.") - return result - - assert self.kind == TypeKind.FUNCTIONPROTO - return ArgumentsIterator(self) - - @property - def element_type(self): - """Retrieve the Type of elements within this Type. - - If accessed on a type that is not an array, complex, or vector type, an - exception will be raised. - """ - result = conf.lib.clang_getElementType(self) - if result.kind == TypeKind.INVALID: - raise Exception('Element type not available on this type.') - - return result - - @property - def element_count(self): - """Retrieve the number of elements in this type. - - Returns an int. - - If the Type is not an array or vector, this raises. - """ - result = conf.lib.clang_getNumElements(self) - if result < 0: - raise Exception('Type does not have elements.') - - return result - - @property - def translation_unit(self): - """The TranslationUnit to which this Type is associated.""" - # If this triggers an AttributeError, the instance was not properly - # instantiated. - return self._tu - - @staticmethod - def from_result(res, fn, args): - assert isinstance(res, Type) - - tu = None - for arg in args: - if hasattr(arg, 'translation_unit'): - tu = arg.translation_unit - break - - assert tu is not None - res._tu = tu - - return res - - def get_canonical(self): - """ - Return the canonical type for a Type. - - Clang's type system explicitly models typedefs and all the - ways a specific type can be represented. The canonical type - is the underlying type with all the "sugar" removed. For - example, if 'T' is a typedef for 'int', the canonical type for - 'T' would be 'int'. - """ - return conf.lib.clang_getCanonicalType(self) - - def is_const_qualified(self): - """Determine whether a Type has the "const" qualifier set. - - This does not look through typedefs that may have added "const" - at a different level. - """ - return conf.lib.clang_isConstQualifiedType(self) - - def is_volatile_qualified(self): - """Determine whether a Type has the "volatile" qualifier set. - - This does not look through typedefs that may have added "volatile" - at a different level. - """ - return conf.lib.clang_isVolatileQualifiedType(self) - - def is_restrict_qualified(self): - """Determine whether a Type has the "restrict" qualifier set. - - This does not look through typedefs that may have added "restrict" at - a different level. - """ - return conf.lib.clang_isRestrictQualifiedType(self) - - def is_function_variadic(self): - """Determine whether this function Type is a variadic function type.""" - assert self.kind == TypeKind.FUNCTIONPROTO - - return conf.lib.clang_isFunctionTypeVariadic(self) - - def is_pod(self): - """Determine whether this Type represents plain old data (POD).""" - return conf.lib.clang_isPODType(self) - - def get_pointee(self): - """ - For pointer types, returns the type of the pointee. - """ - return conf.lib.clang_getPointeeType(self) - - def get_declaration(self): - """ - Return the cursor for the declaration of the given type. - """ - return conf.lib.clang_getTypeDeclaration(self) - - def get_result(self): - """ - Retrieve the result type associated with a function type. - """ - return conf.lib.clang_getResultType(self) - - def get_array_element_type(self): - """ - Retrieve the type of the elements of the array type. - """ - return conf.lib.clang_getArrayElementType(self) - - def get_array_size(self): - """ - Retrieve the size of the constant array. - """ - return conf.lib.clang_getArraySize(self) - - def get_class_type(self): - """ - Retrieve the class type of the member pointer type. - """ - return conf.lib.clang_Type_getClassType(self) - - def get_named_type(self): - """ - Retrieve the type named by the qualified-id. - """ - return conf.lib.clang_Type_getNamedType(self) - - def get_align(self): - """ - Retrieve the alignment of the record. - """ - return conf.lib.clang_Type_getAlignOf(self) - - def get_size(self): - """ - Retrieve the size of the record. - """ - return conf.lib.clang_Type_getSizeOf(self) - - def get_offset(self, fieldname): - """ - Retrieve the offset of a field in the record. - """ - return conf.lib.clang_Type_getOffsetOf(self, fieldname) - - def get_ref_qualifier(self): - """ - Retrieve the ref-qualifier of the type. - """ - return RefQualifierKind.from_id( - conf.lib.clang_Type_getCXXRefQualifier(self)) - - def get_fields(self): - """Return an iterator for accessing the fields of this type.""" - - def visitor(field, children): - assert field != conf.lib.clang_getNullCursor() - - # Create reference to TU so it isn't GC'd before Cursor. - field._tu = self._tu - fields.append(field) - return 1 # continue - fields = [] - conf.lib.clang_Type_visitFields(self, - callbacks['fields_visit'](visitor), fields) - return iter(fields) - - def get_exception_specification_kind(self): - """ - Return the kind of the exception specification; a value from - the ExceptionSpecificationKind enumeration. - """ - return ExceptionSpecificationKind.from_id( - conf.lib.clang.getExceptionSpecificationType(self)) - - @property - def spelling(self): - """Retrieve the spelling of this Type.""" - return conf.lib.clang_getTypeSpelling(self) - - def __eq__(self, other): - if type(other) != type(self): - return False - - return conf.lib.clang_equalTypes(self, other) - - def __ne__(self, other): - return not self.__eq__(other) + return result + + assert self.kind == TypeKind.FUNCTIONPROTO + return ArgumentsIterator(self) + + @property + def element_type(self): + """Retrieve the Type of elements within this Type. + + If accessed on a type that is not an array, complex, or vector type, an + exception will be raised. + """ + result = conf.lib.clang_getElementType(self) + if result.kind == TypeKind.INVALID: + raise Exception('Element type not available on this type.') + + return result + + @property + def element_count(self): + """Retrieve the number of elements in this type. + + Returns an int. + + If the Type is not an array or vector, this raises. + """ + result = conf.lib.clang_getNumElements(self) + if result < 0: + raise Exception('Type does not have elements.') + + return result + + @property + def translation_unit(self): + """The TranslationUnit to which this Type is associated.""" + # If this triggers an AttributeError, the instance was not properly + # instantiated. + return self._tu + + @staticmethod + def from_result(res, fn, args): + assert isinstance(res, Type) + + tu = None + for arg in args: + if hasattr(arg, 'translation_unit'): + tu = arg.translation_unit + break + + assert tu is not None + res._tu = tu + + return res + + def get_canonical(self): + """ + Return the canonical type for a Type. + + Clang's type system explicitly models typedefs and all the + ways a specific type can be represented. The canonical type + is the underlying type with all the "sugar" removed. For + example, if 'T' is a typedef for 'int', the canonical type for + 'T' would be 'int'. + """ + return conf.lib.clang_getCanonicalType(self) + + def is_const_qualified(self): + """Determine whether a Type has the "const" qualifier set. + + This does not look through typedefs that may have added "const" + at a different level. + """ + return conf.lib.clang_isConstQualifiedType(self) + + def is_volatile_qualified(self): + """Determine whether a Type has the "volatile" qualifier set. + + This does not look through typedefs that may have added "volatile" + at a different level. + """ + return conf.lib.clang_isVolatileQualifiedType(self) + + def is_restrict_qualified(self): + """Determine whether a Type has the "restrict" qualifier set. + + This does not look through typedefs that may have added "restrict" at + a different level. + """ + return conf.lib.clang_isRestrictQualifiedType(self) + + def is_function_variadic(self): + """Determine whether this function Type is a variadic function type.""" + assert self.kind == TypeKind.FUNCTIONPROTO + + return conf.lib.clang_isFunctionTypeVariadic(self) + + def is_pod(self): + """Determine whether this Type represents plain old data (POD).""" + return conf.lib.clang_isPODType(self) + + def get_pointee(self): + """ + For pointer types, returns the type of the pointee. + """ + return conf.lib.clang_getPointeeType(self) + + def get_declaration(self): + """ + Return the cursor for the declaration of the given type. + """ + return conf.lib.clang_getTypeDeclaration(self) + + def get_result(self): + """ + Retrieve the result type associated with a function type. + """ + return conf.lib.clang_getResultType(self) + + def get_array_element_type(self): + """ + Retrieve the type of the elements of the array type. + """ + return conf.lib.clang_getArrayElementType(self) + + def get_array_size(self): + """ + Retrieve the size of the constant array. + """ + return conf.lib.clang_getArraySize(self) + + def get_class_type(self): + """ + Retrieve the class type of the member pointer type. + """ + return conf.lib.clang_Type_getClassType(self) + + def get_named_type(self): + """ + Retrieve the type named by the qualified-id. + """ + return conf.lib.clang_Type_getNamedType(self) + + def get_align(self): + """ + Retrieve the alignment of the record. + """ + return conf.lib.clang_Type_getAlignOf(self) + + def get_size(self): + """ + Retrieve the size of the record. + """ + return conf.lib.clang_Type_getSizeOf(self) + + def get_offset(self, fieldname): + """ + Retrieve the offset of a field in the record. + """ + return conf.lib.clang_Type_getOffsetOf(self, fieldname) + + def get_ref_qualifier(self): + """ + Retrieve the ref-qualifier of the type. + """ + return RefQualifierKind.from_id( + conf.lib.clang_Type_getCXXRefQualifier(self)) + + def get_fields(self): + """Return an iterator for accessing the fields of this type.""" + + def visitor(field, children): + assert field != conf.lib.clang_getNullCursor() + + # Create reference to TU so it isn't GC'd before Cursor. + field._tu = self._tu + fields.append(field) + return 1 # continue + fields = [] + conf.lib.clang_Type_visitFields(self, + callbacks['fields_visit'](visitor), fields) + return iter(fields) + + def get_exception_specification_kind(self): + """ + Return the kind of the exception specification; a value from + the ExceptionSpecificationKind enumeration. + """ + return ExceptionSpecificationKind.from_id( + conf.lib.clang.getExceptionSpecificationType(self)) + + @property + def spelling(self): + """Retrieve the spelling of this Type.""" + return conf.lib.clang_getTypeSpelling(self) + + def __eq__(self, other): + if type(other) != type(self): + return False + + return conf.lib.clang_equalTypes(self, other) + + def __ne__(self, other): + return not self.__eq__(other) ## CIndex Objects ## @@ -2417,886 +2427,890 @@ def __ne__(self, other): # a void*. class ClangObject(object): - """ - A helper for Clang objects. This class helps act as an intermediary for - the ctypes library and the Clang CIndex library. - """ - def __init__(self, obj): - assert isinstance(obj, c_object_p) and obj - self.obj = self._as_parameter_ = obj + """ + A helper for Clang objects. This class helps act as an intermediary for + the ctypes library and the Clang CIndex library. + """ + def __init__(self, obj): + assert isinstance(obj, c_object_p) and obj + self.obj = self._as_parameter_ = obj - def from_param(self): - return self._as_parameter_ + def from_param(self): + return self._as_parameter_ class _CXUnsavedFile(Structure): - """Helper for passing unsaved file arguments.""" - _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] + """Helper for passing unsaved file arguments.""" + _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] # Functions calls through the python interface are rather slow. Fortunately, # for most symboles, we do not need to perform a function call. Their spelling # never changes and is consequently provided by this spelling cache. SpellingCache = { - # 0: CompletionChunk.Kind("Optional"), - # 1: CompletionChunk.Kind("TypedText"), - # 2: CompletionChunk.Kind("Text"), - # 3: CompletionChunk.Kind("Placeholder"), - # 4: CompletionChunk.Kind("Informative"), - # 5 : CompletionChunk.Kind("CurrentParameter"), - 6: '(', # CompletionChunk.Kind("LeftParen"), - 7: ')', # CompletionChunk.Kind("RightParen"), - 8: '[', # CompletionChunk.Kind("LeftBracket"), - 9: ']', # CompletionChunk.Kind("RightBracket"), - 10: '{', # CompletionChunk.Kind("LeftBrace"), - 11: '}', # CompletionChunk.Kind("RightBrace"), - 12: '<', # CompletionChunk.Kind("LeftAngle"), - 13: '>', # CompletionChunk.Kind("RightAngle"), - 14: ', ', # CompletionChunk.Kind("Comma"), - # 15: CompletionChunk.Kind("ResultType"), - 16: ':', # CompletionChunk.Kind("Colon"), - 17: ';', # CompletionChunk.Kind("SemiColon"), - 18: '=', # CompletionChunk.Kind("Equal"), - 19: ' ', # CompletionChunk.Kind("HorizontalSpace"), - # 20: CompletionChunk.Kind("VerticalSpace") + # 0: CompletionChunk.Kind("Optional"), + # 1: CompletionChunk.Kind("TypedText"), + # 2: CompletionChunk.Kind("Text"), + # 3: CompletionChunk.Kind("Placeholder"), + # 4: CompletionChunk.Kind("Informative"), + # 5 : CompletionChunk.Kind("CurrentParameter"), + 6: '(', # CompletionChunk.Kind("LeftParen"), + 7: ')', # CompletionChunk.Kind("RightParen"), + 8: '[', # CompletionChunk.Kind("LeftBracket"), + 9: ']', # CompletionChunk.Kind("RightBracket"), + 10: '{', # CompletionChunk.Kind("LeftBrace"), + 11: '}', # CompletionChunk.Kind("RightBrace"), + 12: '<', # CompletionChunk.Kind("LeftAngle"), + 13: '>', # CompletionChunk.Kind("RightAngle"), + 14: ', ', # CompletionChunk.Kind("Comma"), + # 15: CompletionChunk.Kind("ResultType"), + 16: ':', # CompletionChunk.Kind("Colon"), + 17: ';', # CompletionChunk.Kind("SemiColon"), + 18: '=', # CompletionChunk.Kind("Equal"), + 19: ' ', # CompletionChunk.Kind("HorizontalSpace"), + # 20: CompletionChunk.Kind("VerticalSpace") } class CompletionChunk: - class Kind: - def __init__(self, name): - self.name = name + class Kind: + def __init__(self, name): + self.name = name - def __str__(self): - return self.name + def __str__(self): + return self.name - def __repr__(self): - return "" % self + def __repr__(self): + return "" % self - def __init__(self, completionString, key): - self.cs = completionString - self.key = key - self.__kindNumberCache = -1 + def __init__(self, completionString, key): + self.cs = completionString + self.key = key + self.__kindNumberCache = -1 - def __repr__(self): - return "{'" + self.spelling + "', " + str(self.kind) + "}" + def __repr__(self): + return "{'" + self.spelling + "', " + str(self.kind) + "}" - @CachedProperty - def spelling(self): - if self.__kindNumber in SpellingCache: - return SpellingCache[self.__kindNumber] - return conf.lib.clang_getCompletionChunkText(self.cs, self.key) + @CachedProperty + def spelling(self): + if self.__kindNumber in SpellingCache: + return SpellingCache[self.__kindNumber] + return conf.lib.clang_getCompletionChunkText(self.cs, self.key) - # We do not use @CachedProperty here, as the manual implementation is - # apparently still significantly faster. Please profile carefully if you - # would like to add CachedProperty back. - @property - def __kindNumber(self): - if self.__kindNumberCache == -1: - self.__kindNumberCache = \ - conf.lib.clang_getCompletionChunkKind(self.cs, self.key) - return self.__kindNumberCache + # We do not use @CachedProperty here, as the manual implementation is + # apparently still significantly faster. Please profile carefully if you + # would like to add CachedProperty back. + @property + def __kindNumber(self): + if self.__kindNumberCache == -1: + self.__kindNumberCache = \ + conf.lib.clang_getCompletionChunkKind(self.cs, self.key) + return self.__kindNumberCache - @CachedProperty - def kind(self): - return completionChunkKindMap[self.__kindNumber] + @CachedProperty + def kind(self): + return completionChunkKindMap[self.__kindNumber] - @CachedProperty - def string(self): - res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, - self.key) + @CachedProperty + def string(self): + res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, + self.key) - if (res): - return CompletionString(res) - else: - None + if (res): + return CompletionString(res) + else: + None - def isKindOptional(self): - return self.__kindNumber == 0 + def isKindOptional(self): + return self.__kindNumber == 0 - def isKindTypedText(self): - return self.__kindNumber == 1 + def isKindTypedText(self): + return self.__kindNumber == 1 - def isKindPlaceHolder(self): - return self.__kindNumber == 3 + def isKindPlaceHolder(self): + return self.__kindNumber == 3 - def isKindInformative(self): - return self.__kindNumber == 4 + def isKindInformative(self): + return self.__kindNumber == 4 - def isKindResultType(self): - return self.__kindNumber == 15 + def isKindResultType(self): + return self.__kindNumber == 15 completionChunkKindMap = { - 0: CompletionChunk.Kind("Optional"), - 1: CompletionChunk.Kind("TypedText"), - 2: CompletionChunk.Kind("Text"), - 3: CompletionChunk.Kind("Placeholder"), - 4: CompletionChunk.Kind("Informative"), - 5: CompletionChunk.Kind("CurrentParameter"), - 6: CompletionChunk.Kind("LeftParen"), - 7: CompletionChunk.Kind("RightParen"), - 8: CompletionChunk.Kind("LeftBracket"), - 9: CompletionChunk.Kind("RightBracket"), - 10: CompletionChunk.Kind("LeftBrace"), - 11: CompletionChunk.Kind("RightBrace"), - 12: CompletionChunk.Kind("LeftAngle"), - 13: CompletionChunk.Kind("RightAngle"), - 14: CompletionChunk.Kind("Comma"), - 15: CompletionChunk.Kind("ResultType"), - 16: CompletionChunk.Kind("Colon"), - 17: CompletionChunk.Kind("SemiColon"), - 18: CompletionChunk.Kind("Equal"), - 19: CompletionChunk.Kind("HorizontalSpace"), - 20: CompletionChunk.Kind("VerticalSpace")} + 0: CompletionChunk.Kind("Optional"), + 1: CompletionChunk.Kind("TypedText"), + 2: CompletionChunk.Kind("Text"), + 3: CompletionChunk.Kind("Placeholder"), + 4: CompletionChunk.Kind("Informative"), + 5: CompletionChunk.Kind("CurrentParameter"), + 6: CompletionChunk.Kind("LeftParen"), + 7: CompletionChunk.Kind("RightParen"), + 8: CompletionChunk.Kind("LeftBracket"), + 9: CompletionChunk.Kind("RightBracket"), + 10: CompletionChunk.Kind("LeftBrace"), + 11: CompletionChunk.Kind("RightBrace"), + 12: CompletionChunk.Kind("LeftAngle"), + 13: CompletionChunk.Kind("RightAngle"), + 14: CompletionChunk.Kind("Comma"), + 15: CompletionChunk.Kind("ResultType"), + 16: CompletionChunk.Kind("Colon"), + 17: CompletionChunk.Kind("SemiColon"), + 18: CompletionChunk.Kind("Equal"), + 19: CompletionChunk.Kind("HorizontalSpace"), + 20: CompletionChunk.Kind("VerticalSpace")} class CompletionString(ClangObject): - class Availability: - def __init__(self, name): - self.name = name + class Availability: + def __init__(self, name): + self.name = name - def __str__(self): - return self.name + def __str__(self): + return self.name - def __repr__(self): - return "" % self + def __repr__(self): + return "" % self - def __len__(self): - return self.num_chunks + def __len__(self): + return self.num_chunks - @CachedProperty - def num_chunks(self): - return conf.lib.clang_getNumCompletionChunks(self.obj) + @CachedProperty + def num_chunks(self): + return conf.lib.clang_getNumCompletionChunks(self.obj) - def __getitem__(self, key): - if self.num_chunks <= key: - raise IndexError - return CompletionChunk(self.obj, key) + def __getitem__(self, key): + if self.num_chunks <= key: + raise IndexError + return CompletionChunk(self.obj, key) - @property - def priority(self): - return conf.lib.clang_getCompletionPriority(self.obj) + @property + def priority(self): + return conf.lib.clang_getCompletionPriority(self.obj) - @property - def availability(self): - res = conf.lib.clang_getCompletionAvailability(self.obj) - return availabilityKinds[res] + @property + def availability(self): + res = conf.lib.clang_getCompletionAvailability(self.obj) + return availabilityKinds[res] - @property - def briefComment(self): - if conf.function_exists("clang_getCompletionBriefComment"): - return conf.lib.clang_getCompletionBriefComment(self.obj) - return _CXString() + @property + def briefComment(self): + if conf.function_exists("clang_getCompletionBriefComment"): + return conf.lib.clang_getCompletionBriefComment(self.obj) + return _CXString() - def __repr__(self): - return " | ".join([str(a) for a in self]) \ - + " || Priority: " + str(self.priority) \ - + " || Availability: " + str(self.availability) \ - + " || Brief comment: " + str(self.briefComment) + def __repr__(self): + return " | ".join([str(a) for a in self]) \ + + " || Priority: " + str(self.priority) \ + + " || Availability: " + str(self.availability) \ + + " || Brief comment: " + str(self.briefComment) availabilityKinds = { - 0: CompletionChunk.Kind("Available"), - 1: CompletionChunk.Kind("Deprecated"), - 2: CompletionChunk.Kind("NotAvailable"), - 3: CompletionChunk.Kind("NotAccessible")} + 0: CompletionChunk.Kind("Available"), + 1: CompletionChunk.Kind("Deprecated"), + 2: CompletionChunk.Kind("NotAvailable"), + 3: CompletionChunk.Kind("NotAccessible")} class CodeCompletionResult(Structure): - _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] + _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] - def __repr__(self): - return str(CompletionString(self.completionString)) + def __repr__(self): + return str(CompletionString(self.completionString)) - @property - def kind(self): - return CursorKind.from_id(self.cursorKind) + @property + def kind(self): + return CursorKind.from_id(self.cursorKind) - @property - def string(self): - return CompletionString(self.completionString) + @property + def string(self): + return CompletionString(self.completionString) class CCRStructure(Structure): - _fields_ = [('results', POINTER(CodeCompletionResult)), - ('numResults', c_int)] + _fields_ = [('results', POINTER(CodeCompletionResult)), + ('numResults', c_int)] - def __len__(self): - return self.numResults + def __len__(self): + return self.numResults - def __getitem__(self, key): - if len(self) <= key: - raise IndexError + def __getitem__(self, key): + if len(self) <= key: + raise IndexError - return self.results[key] + return self.results[key] class CodeCompletionResults(ClangObject): - def __init__(self, ptr): - assert isinstance(ptr, POINTER(CCRStructure)) and ptr - self.ptr = self._as_parameter_ = ptr + def __init__(self, ptr): + assert isinstance(ptr, POINTER(CCRStructure)) and ptr + self.ptr = self._as_parameter_ = ptr - def from_param(self): - return self._as_parameter_ + def from_param(self): + return self._as_parameter_ - def __del__(self): - conf.lib.clang_disposeCodeCompleteResults(self) + def __del__(self): + conf.lib.clang_disposeCodeCompleteResults(self) - @property - def results(self): - return self.ptr.contents + @property + def results(self): + return self.ptr.contents - @property - def diagnostics(self): - class DiagnosticsItr: - def __init__(self, ccr): - self.ccr= ccr + @property + def diagnostics(self): + class DiagnosticsItr: + def __init__(self, ccr): + self.ccr= ccr - def __len__(self): - return int(\ - conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) + def __len__(self): + return int(\ + conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) - def __getitem__(self, key): - return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) + def __getitem__(self, key): + return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) - return DiagnosticsItr(self) + return DiagnosticsItr(self) class Index(ClangObject): - """ - The Index type provides the primary interface to the Clang CIndex library, - primarily by providing an interface for reading and parsing translation - units. - """ - - @staticmethod - def create(excludeDecls=False): - """ - Create a new Index. - Parameters: - excludeDecls -- Exclude local declarations from translation units. - """ - return Index(conf.lib.clang_createIndex(excludeDecls, 0)) - - def __del__(self): - conf.lib.clang_disposeIndex(self) - - def read(self, path): - """Load a TranslationUnit from the given AST file.""" - return TranslationUnit.from_ast_file(path, self) - - def parse(self, path, args=None, unsaved_files=None, options = 0): - """Load the translation unit from the given source code file by running - clang and generating the AST before loading. Additional command line - parameters can be passed to clang via the args parameter. - - In-memory contents for files can be provided by passing a list of pairs - to as unsaved_files, the first item should be the filenames to be mapped - and the second should be the contents to be substituted for the - file. The contents may be passed as strings or file objects. - - If an error was encountered during parsing, a TranslationUnitLoadError - will be raised. - """ - return TranslationUnit.from_source(path, args, unsaved_files, options, - self) + """ + The Index type provides the primary interface to the Clang CIndex library, + primarily by providing an interface for reading and parsing translation + units. + """ + + @staticmethod + def create(excludeDecls=False): + """ + Create a new Index. + Parameters: + excludeDecls -- Exclude local declarations from translation units. + """ + return Index(conf.lib.clang_createIndex(excludeDecls, 0)) + + def __del__(self): + conf.lib.clang_disposeIndex(self) + + def read(self, path): + """Load a TranslationUnit from the given AST file.""" + return TranslationUnit.from_ast_file(path, self) + + def parse(self, path, args=None, unsaved_files=None, options = 0): + """Load the translation unit from the given source code file by running + clang and generating the AST before loading. Additional command line + parameters can be passed to clang via the args parameter. + + In-memory contents for files can be provided by passing a list of pairs + to as unsaved_files, the first item should be the filenames to be mapped + and the second should be the contents to be substituted for the + file. The contents may be passed as strings or file objects. + + If an error was encountered during parsing, a TranslationUnitLoadError + will be raised. + """ + return TranslationUnit.from_source(path, args, unsaved_files, options, + self) class TranslationUnit(ClangObject): - """Represents a source code translation unit. - - This is one of the main types in the API. Any time you wish to interact - with Clang's representation of a source file, you typically start with a - translation unit. - """ - - # Default parsing mode. - PARSE_NONE = 0 - - # Instruct the parser to create a detailed processing record containing - # metadata not normally retained. - PARSE_DETAILED_PROCESSING_RECORD = 1 - - # Indicates that the translation unit is incomplete. This is typically used - # when parsing headers. - PARSE_INCOMPLETE = 2 + """Represents a source code translation unit. - # Instruct the parser to create a pre-compiled preamble for the translation - # unit. This caches the preamble (included files at top of source file). - # This is useful if the translation unit will be reparsed and you don't - # want to incur the overhead of reparsing the preamble. - PARSE_PRECOMPILED_PREAMBLE = 4 + This is one of the main types in the API. Any time you wish to interact + with Clang's representation of a source file, you typically start with a + translation unit. + """ - # Cache code completion information on parse. This adds time to parsing but - # speeds up code completion. - PARSE_CACHE_COMPLETION_RESULTS = 8 + # Default parsing mode. + PARSE_NONE = 0 - # Flags with values 16 and 32 are deprecated and intentionally omitted. + # Instruct the parser to create a detailed processing record containing + # metadata not normally retained. + PARSE_DETAILED_PROCESSING_RECORD = 1 - # Do not parse function bodies. This is useful if you only care about - # searching for declarations/definitions. - PARSE_SKIP_FUNCTION_BODIES = 64 + # Indicates that the translation unit is incomplete. This is typically used + # when parsing headers. + PARSE_INCOMPLETE = 2 - # Used to indicate that brief documentation comments should be included - # into the set of code completions returned from this translation unit. - PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 + # Instruct the parser to create a pre-compiled preamble for the translation + # unit. This caches the preamble (included files at top of source file). + # This is useful if the translation unit will be reparsed and you don't + # want to incur the overhead of reparsing the preamble. + PARSE_PRECOMPILED_PREAMBLE = 4 - @classmethod - def from_source(cls, filename, args=None, unsaved_files=None, options=0, - index=None): - """Create a TranslationUnit by parsing source. + # Cache code completion information on parse. This adds time to parsing but + # speeds up code completion. + PARSE_CACHE_COMPLETION_RESULTS = 8 - This is capable of processing source code both from files on the - filesystem as well as in-memory contents. + # Flags with values 16 and 32 are deprecated and intentionally omitted. - Command-line arguments that would be passed to clang are specified as - a list via args. These can be used to specify include paths, warnings, - etc. e.g. ["-Wall", "-I/path/to/include"]. + # Do not parse function bodies. This is useful if you only care about + # searching for declarations/definitions. + PARSE_SKIP_FUNCTION_BODIES = 64 - In-memory file content can be provided via unsaved_files. This is an - iterable of 2-tuples. The first element is the str filename. The - second element defines the content. Content can be provided as str - source code or as file objects (anything with a read() method). If - a file object is being used, content will be read until EOF and the - read cursor will not be reset to its original position. + # Used to indicate that brief documentation comments should be included + # into the set of code completions returned from this translation unit. + PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 - options is a bitwise or of TranslationUnit.PARSE_XXX flags which will - control parsing behavior. + @classmethod + def from_source(cls, filename, args=None, unsaved_files=None, options=0, + index=None): + """Create a TranslationUnit by parsing source. - index is an Index instance to utilize. If not provided, a new Index - will be created for this TranslationUnit. + This is capable of processing source code both from files on the + filesystem as well as in-memory contents. - To parse source from the filesystem, the filename of the file to parse - is specified by the filename argument. Or, filename could be None and - the args list would contain the filename(s) to parse. - - To parse source from an in-memory buffer, set filename to the virtual - filename you wish to associate with this source (e.g. "test.c"). The - contents of that file are then provided in unsaved_files. - - If an error occurs, a TranslationUnitLoadError is raised. - - Please note that a TranslationUnit with parser errors may be returned. - It is the caller's responsibility to check tu.diagnostics for errors. - - Also note that Clang infers the source language from the extension of - the input filename. If you pass in source code containing a C++ class - declaration with the filename "test.c" parsing will fail. - """ - if args is None: - args = [] + Command-line arguments that would be passed to clang are specified as + a list via args. These can be used to specify include paths, warnings, + etc. e.g. ["-Wall", "-I/path/to/include"]. - if unsaved_files is None: - unsaved_files = [] + In-memory file content can be provided via unsaved_files. This is an + iterable of 2-tuples. The first element is the str filename. The + second element defines the content. Content can be provided as str + source code or as file objects (anything with a read() method). If + a file object is being used, content will be read until EOF and the + read cursor will not be reset to its original position. - if index is None: - index = Index.create() + options is a bitwise or of TranslationUnit.PARSE_XXX flags which will + control parsing behavior. - args_array = None - if len(args) > 0: - args_array = (c_char_p * len(args))(*[b(x) for x in args]) - - unsaved_array = None - if len(unsaved_files) > 0: - unsaved_array = (_CXUnsavedFile * len(unsaved_files))() - for i, (name, contents) in enumerate(unsaved_files): - if hasattr(contents, "read"): - contents = contents.read() + index is an Index instance to utilize. If not provided, a new Index + will be created for this TranslationUnit. - unsaved_array[i].name = b(name) - unsaved_array[i].contents = b(contents) - unsaved_array[i].length = len(contents) + To parse source from the filesystem, the filename of the file to parse + is specified by the filename argument. Or, filename could be None and + the args list would contain the filename(s) to parse. + + To parse source from an in-memory buffer, set filename to the virtual + filename you wish to associate with this source (e.g. "test.c"). The + contents of that file are then provided in unsaved_files. + + If an error occurs, a TranslationUnitLoadError is raised. + + Please note that a TranslationUnit with parser errors may be returned. + It is the caller's responsibility to check tu.diagnostics for errors. + + Also note that Clang infers the source language from the extension of + the input filename. If you pass in source code containing a C++ class + declaration with the filename "test.c" parsing will fail. + """ + if args is None: + args = [] + + if unsaved_files is None: + unsaved_files = [] + + if index is None: + index = Index.create() - ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array, - len(args), unsaved_array, - len(unsaved_files), options) + args_array = None + if len(args) > 0: + args_array = (c_char_p * len(args))(*[b(x) for x in args]) + + unsaved_array = None + if len(unsaved_files) > 0: + unsaved_array = (_CXUnsavedFile * len(unsaved_files))() + for i, (name, contents) in enumerate(unsaved_files): + if hasattr(contents, "read"): + contents = contents.read() - if not ptr: - raise TranslationUnitLoadError("Error parsing translation unit.") + unsaved_array[i].name = b(name) + unsaved_array[i].contents = b(contents) + unsaved_array[i].length = len(contents) - return cls(ptr, index=index) + ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array, + len(args), unsaved_array, + len(unsaved_files), options) - @classmethod - def from_ast_file(cls, filename, index=None): - """Create a TranslationUnit instance from a saved AST file. + if not ptr: + conf.unload_lib() + raise TranslationUnitLoadError("Error parsing translation unit.") - A previously-saved AST file (provided with -emit-ast or - TranslationUnit.save()) is loaded from the filename specified. + return cls(ptr, index=index) - If the file cannot be loaded, a TranslationUnitLoadError will be - raised. + @classmethod + def from_ast_file(cls, filename, index=None): + """Create a TranslationUnit instance from a saved AST file. - index is optional and is the Index instance to use. If not provided, - a default Index will be created. - """ - if index is None: - index = Index.create() + A previously-saved AST file (provided with -emit-ast or + TranslationUnit.save()) is loaded from the filename specified. - ptr = conf.lib.clang_createTranslationUnit(index, filename) - if not ptr: - raise TranslationUnitLoadError(filename) + If the file cannot be loaded, a TranslationUnitLoadError will be + raised. - return cls(ptr=ptr, index=index) + index is optional and is the Index instance to use. If not provided, + a default Index will be created. + """ + if index is None: + index = Index.create() - def __init__(self, ptr, index): - """Create a TranslationUnit instance. + ptr = conf.lib.clang_createTranslationUnit(index, filename) + if not ptr: + raise TranslationUnitLoadError(filename) - TranslationUnits should be created using one of the from_* @classmethod - functions above. __init__ is only called internally. - """ - assert isinstance(index, Index) - self.index = index - ClangObject.__init__(self, ptr) + return cls(ptr=ptr, index=index) + + def __init__(self, ptr, index): + """Create a TranslationUnit instance. - def __del__(self): - conf.lib.clang_disposeTranslationUnit(self) + TranslationUnits should be created using one of the from_* @classmethod + functions above. __init__ is only called internally. + """ + assert isinstance(index, Index) + self.index = index + ClangObject.__init__(self, ptr) - @property - def cursor(self): - """Retrieve the cursor that represents the given translation unit.""" - return conf.lib.clang_getTranslationUnitCursor(self) + def __del__(self): + conf.lib.clang_disposeTranslationUnit(self) - @property - def spelling(self): - """Get the original translation unit source file name.""" - return conf.lib.clang_getTranslationUnitSpelling(self) + @property + def cursor(self): + """Retrieve the cursor that represents the given translation unit.""" + return conf.lib.clang_getTranslationUnitCursor(self) - def get_includes(self): - """ - Return an iterable sequence of FileInclusion objects that describe the - sequence of inclusions in a translation unit. The first object in - this sequence is always the input file. Note that this method will not - recursively iterate over header files included through precompiled - headers. - """ - def visitor(fobj, lptr, depth, includes): - if depth > 0: - loc = lptr.contents - includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) + @property + def spelling(self): + """Get the original translation unit source file name.""" + return conf.lib.clang_getTranslationUnitSpelling(self) - # Automatically adapt CIndex/ctype pointers to python objects - includes = [] - conf.lib.clang_getInclusions(self, - callbacks['translation_unit_includes'](visitor), includes) - - return iter(includes) - - def get_file(self, filename): - """Obtain a File from this translation unit.""" - - return File.from_name(self, filename) - - def get_location(self, filename, position): - """Obtain a SourceLocation for a file in this translation unit. - - The position can be specified by passing: - - - Integer file offset. Initial file offset is 0. - - 2-tuple of (line number, column number). Initial file position is - (0, 0) - """ - f = self.get_file(filename) - - if isinstance(position, int): - return SourceLocation.from_offset(self, f, position) - - return SourceLocation.from_position(self, f, position[0], position[1]) - - def get_extent(self, filename, locations): - """Obtain a SourceRange from this translation unit. - - The bounds of the SourceRange must ultimately be defined by a start and - end SourceLocation. For the locations argument, you can pass: - - - 2 SourceLocation instances in a 2-tuple or list. - - 2 int file offsets via a 2-tuple or list. - - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. - - e.g. - - get_extent('foo.c', (5, 10)) - get_extent('foo.c', ((1, 1), (1, 15))) - """ - f = self.get_file(filename) - - if len(locations) < 2: - raise Exception('Must pass object with at least 2 elements') - - start_location, end_location = locations - - if hasattr(start_location, '__len__'): - start_location = SourceLocation.from_position(self, f, - start_location[0], start_location[1]) - elif isinstance(start_location, int): - start_location = SourceLocation.from_offset(self, f, - start_location) - - if hasattr(end_location, '__len__'): - end_location = SourceLocation.from_position(self, f, - end_location[0], end_location[1]) - elif isinstance(end_location, int): - end_location = SourceLocation.from_offset(self, f, end_location) - - assert isinstance(start_location, SourceLocation) - assert isinstance(end_location, SourceLocation) - - return SourceRange.from_locations(start_location, end_location) - - @property - def diagnostics(self): - """ - Return an iterable (and indexable) object containing the diagnostics. - """ - class DiagIterator: - def __init__(self, tu): - self.tu = tu - - def __len__(self): - return int(conf.lib.clang_getNumDiagnostics(self.tu)) - - def __getitem__(self, key): - diag = conf.lib.clang_getDiagnostic(self.tu, key) - if not diag: - raise IndexError - return Diagnostic(diag) - - return DiagIterator(self) - - def reparse(self, unsaved_files=None, options=0): - """ - Reparse an already parsed translation unit. - - In-memory contents for files can be provided by passing a list of pairs - as unsaved_files, the first items should be the filenames to be mapped - and the second should be the contents to be substituted for the - file. The contents may be passed as strings or file objects. - """ - if unsaved_files is None: - unsaved_files = [] - - unsaved_files_array = 0 - if len(unsaved_files): - unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() - for i,(name,value) in enumerate(unsaved_files): - if not isinstance(value, str): - # FIXME: It would be great to support an efficient version - # of this, one day. - value = value.read() - print(value) - if not isinstance(value, str): - raise TypeError('Unexpected unsaved file contents.') - unsaved_files_array[i].name = name - unsaved_files_array[i].contents = value - unsaved_files_array[i].length = len(value) - ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), - unsaved_files_array, options) - - def save(self, filename): - """Saves the TranslationUnit to a file. - - This is equivalent to passing -emit-ast to the clang frontend. The - saved file can be loaded back into a TranslationUnit. Or, if it - corresponds to a header, it can be used as a pre-compiled header file. - - If an error occurs while saving, a TranslationUnitSaveError is raised. - If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means - the constructed TranslationUnit was not valid at time of save. In this - case, the reason(s) why should be available via - TranslationUnit.diagnostics(). - - filename -- The path to save the translation unit to. - """ - options = conf.lib.clang_defaultSaveOptions(self) - result = int(conf.lib.clang_saveTranslationUnit(self, filename, - options)) - if result != 0: - raise TranslationUnitSaveError(result, - 'Error saving TranslationUnit.') - - def codeComplete(self, path, line, column, unsaved_files=None, - include_macros=False, include_code_patterns=False, - include_brief_comments=False): - """ - Code complete in this translation unit. - - In-memory contents for files can be provided by passing a list of pairs - as unsaved_files, the first items should be the filenames to be mapped - and the second should be the contents to be substituted for the - file. The contents may be passed as strings or file objects. - """ - options = 0 - - if include_macros: - options += 1 - - if include_code_patterns: - options += 2 - - if include_brief_comments: - options += 4 - - if unsaved_files is None: - unsaved_files = [] - - unsaved_files_array = 0 - if len(unsaved_files): - unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() - for i,(name,value) in enumerate(unsaved_files): - if not isinstance(value, str): - # FIXME: It would be great to support an efficient version - # of this, one day. - value = value.read() - print(value) - if not isinstance(value, str): - raise TypeError('Unexpected unsaved file contents.') - unsaved_files_array[i].name = b(name) - unsaved_files_array[i].contents = b(value) - unsaved_files_array[i].length = len(value) - ptr = conf.lib.clang_codeCompleteAt(self, path, line, column, - unsaved_files_array, len(unsaved_files), options) - if ptr: - return CodeCompletionResults(ptr) - return None - - def get_tokens(self, locations=None, extent=None): - """Obtain tokens in this translation unit. - - This is a generator for Token instances. The caller specifies a range - of source code to obtain tokens for. The range can be specified as a - 2-tuple of SourceLocation or as a SourceRange. If both are defined, - behavior is undefined. - """ - if locations is not None: - extent = SourceRange(start=locations[0], end=locations[1]) - - return TokenGroup.get_tokens(self, extent) + def get_includes(self): + """ + Return an iterable sequence of FileInclusion objects that describe the + sequence of inclusions in a translation unit. The first object in + this sequence is always the input file. Note that this method will not + recursively iterate over header files included through precompiled + headers. + """ + def visitor(fobj, lptr, depth, includes): + if depth > 0: + loc = lptr.contents + includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) + + # Automatically adapt CIndex/ctype pointers to python objects + includes = [] + conf.lib.clang_getInclusions(self, + callbacks['translation_unit_includes'](visitor), includes) + + return iter(includes) + + def get_file(self, filename): + """Obtain a File from this translation unit.""" + + return File.from_name(self, filename) + + def get_location(self, filename, position): + """Obtain a SourceLocation for a file in this translation unit. + + The position can be specified by passing: + + - Integer file offset. Initial file offset is 0. + - 2-tuple of (line number, column number). Initial file position is + (0, 0) + """ + f = self.get_file(filename) + + if isinstance(position, int): + return SourceLocation.from_offset(self, f, position) + + return SourceLocation.from_position(self, f, position[0], position[1]) + + def get_extent(self, filename, locations): + """Obtain a SourceRange from this translation unit. + + The bounds of the SourceRange must ultimately be defined by a start and + end SourceLocation. For the locations argument, you can pass: + + - 2 SourceLocation instances in a 2-tuple or list. + - 2 int file offsets via a 2-tuple or list. + - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. + + e.g. + + get_extent('foo.c', (5, 10)) + get_extent('foo.c', ((1, 1), (1, 15))) + """ + f = self.get_file(filename) + + if len(locations) < 2: + raise Exception('Must pass object with at least 2 elements') + + start_location, end_location = locations + + if hasattr(start_location, '__len__'): + start_location = SourceLocation.from_position(self, f, + start_location[0], start_location[1]) + elif isinstance(start_location, int): + start_location = SourceLocation.from_offset(self, f, + start_location) + + if hasattr(end_location, '__len__'): + end_location = SourceLocation.from_position(self, f, + end_location[0], end_location[1]) + elif isinstance(end_location, int): + end_location = SourceLocation.from_offset(self, f, end_location) + else: + end_location = SourceLocation.from_offset(self, f, int(end_location)) + + + assert isinstance(start_location, SourceLocation) + assert isinstance(end_location, SourceLocation) + + return SourceRange.from_locations(start_location, end_location) + + @property + def diagnostics(self): + """ + Return an iterable (and indexable) object containing the diagnostics. + """ + class DiagIterator: + def __init__(self, tu): + self.tu = tu + + def __len__(self): + return int(conf.lib.clang_getNumDiagnostics(self.tu)) + + def __getitem__(self, key): + diag = conf.lib.clang_getDiagnostic(self.tu, key) + if not diag: + raise IndexError + return Diagnostic(diag) + + return DiagIterator(self) + + def reparse(self, unsaved_files=None, options=0): + """ + Reparse an already parsed translation unit. + + In-memory contents for files can be provided by passing a list of pairs + as unsaved_files, the first items should be the filenames to be mapped + and the second should be the contents to be substituted for the + file. The contents may be passed as strings or file objects. + """ + if unsaved_files is None: + unsaved_files = [] + + unsaved_files_array = 0 + if len(unsaved_files): + unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() + for i,(name,value) in enumerate(unsaved_files): + if not isinstance(value, str): + # FIXME: It would be great to support an efficient version + # of this, one day. + value = value.read() + print(value) + if not isinstance(value, str): + raise TypeError('Unexpected unsaved file contents.') + unsaved_files_array[i].name = name + unsaved_files_array[i].contents = value + unsaved_files_array[i].length = len(value) + ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), + unsaved_files_array, options) + + def save(self, filename): + """Saves the TranslationUnit to a file. + + This is equivalent to passing -emit-ast to the clang frontend. The + saved file can be loaded back into a TranslationUnit. Or, if it + corresponds to a header, it can be used as a pre-compiled header file. + + If an error occurs while saving, a TranslationUnitSaveError is raised. + If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means + the constructed TranslationUnit was not valid at time of save. In this + case, the reason(s) why should be available via + TranslationUnit.diagnostics(). + + filename -- The path to save the translation unit to. + """ + options = conf.lib.clang_defaultSaveOptions(self) + result = int(conf.lib.clang_saveTranslationUnit(self, filename, + options)) + if result != 0: + raise TranslationUnitSaveError(result, + 'Error saving TranslationUnit.') + + def codeComplete(self, path, line, column, unsaved_files=None, + include_macros=False, include_code_patterns=False, + include_brief_comments=False): + """ + Code complete in this translation unit. + + In-memory contents for files can be provided by passing a list of pairs + as unsaved_files, the first items should be the filenames to be mapped + and the second should be the contents to be substituted for the + file. The contents may be passed as strings or file objects. + """ + options = 0 + + if include_macros: + options += 1 + + if include_code_patterns: + options += 2 + + if include_brief_comments: + options += 4 + + if unsaved_files is None: + unsaved_files = [] + + unsaved_files_array = 0 + if len(unsaved_files): + unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() + for i,(name,value) in enumerate(unsaved_files): + if not isinstance(value, str): + # FIXME: It would be great to support an efficient version + # of this, one day. + value = value.read() + print(value) + if not isinstance(value, str): + raise TypeError('Unexpected unsaved file contents.') + unsaved_files_array[i].name = b(name) + unsaved_files_array[i].contents = b(value) + unsaved_files_array[i].length = len(value) + ptr = conf.lib.clang_codeCompleteAt(self, path, line, column, + unsaved_files_array, len(unsaved_files), options) + if ptr: + return CodeCompletionResults(ptr) + return None + + def get_tokens(self, locations=None, extent=None): + """Obtain tokens in this translation unit. + + This is a generator for Token instances. The caller specifies a range + of source code to obtain tokens for. The range can be specified as a + 2-tuple of SourceLocation or as a SourceRange. If both are defined, + behavior is undefined. + """ + if locations is not None: + extent = SourceRange(start=locations[0], end=locations[1]) + + return TokenGroup.get_tokens(self, extent) class File(ClangObject): - """ - The File class represents a particular source file that is part of a - translation unit. - """ + """ + The File class represents a particular source file that is part of a + translation unit. + """ - @staticmethod - def from_name(translation_unit, file_name): - """Retrieve a file handle within the given translation unit.""" - return File(conf.lib.clang_getFile(translation_unit, file_name)) + @staticmethod + def from_name(translation_unit, file_name): + """Retrieve a file handle within the given translation unit.""" + return File(conf.lib.clang_getFile(translation_unit, file_name)) - @property - def name(self): - """Return the complete file and path name of the file.""" - return conf.lib.clang_getFileName(self) + @property + def name(self): + """Return the complete file and path name of the file.""" + return conf.lib.clang_getFileName(self) - @property - def time(self): - """Return the last modification time of the file.""" - return conf.lib.clang_getFileTime(self) + @property + def time(self): + """Return the last modification time of the file.""" + return conf.lib.clang_getFileTime(self) - def __str__(self): - return self.name + def __str__(self): + return self.name - def __repr__(self): - return "" % (self.name) + def __repr__(self): + return "" % (self.name) - @staticmethod - def from_cursor_result(res, fn, args): - assert isinstance(res, File) + @staticmethod + def from_cursor_result(res, fn, args): + assert isinstance(res, File) - # Copy a reference to the TranslationUnit to prevent premature GC. - res._tu = args[0]._tu - return res + # Copy a reference to the TranslationUnit to prevent premature GC. + res._tu = args[0]._tu + return res class FileInclusion(object): - """ - The FileInclusion class represents the inclusion of one source file by - another via a '#include' directive or as the input file for the translation - unit. This class provides information about the included file, the including - file, the location of the '#include' directive and the depth of the included - file in the stack. Note that the input file has depth 0. - """ - - def __init__(self, src, tgt, loc, depth): - self.source = src - self.include = tgt - self.location = loc - self.depth = depth - - @property - def is_input_file(self): - """True if the included file is the input file.""" - return self.depth == 0 + """ + The FileInclusion class represents the inclusion of one source file by + another via a '#include' directive or as the input file for the translation + unit. This class provides information about the included file, the including + file, the location of the '#include' directive and the depth of the included + file in the stack. Note that the input file has depth 0. + """ + + def __init__(self, src, tgt, loc, depth): + self.source = src + self.include = tgt + self.location = loc + self.depth = depth + + @property + def is_input_file(self): + """True if the included file is the input file.""" + return self.depth == 0 class CompilationDatabaseError(Exception): - """Represents an error that occurred when working with a CompilationDatabase + """Represents an error that occurred when working with a CompilationDatabase - Each error is associated to an enumerated value, accessible under - e.cdb_error. Consumers can compare the value with one of the ERROR_ - constants in this class. - """ + Each error is associated to an enumerated value, accessible under + e.cdb_error. Consumers can compare the value with one of the ERROR_ + constants in this class. + """ - # An unknown error occurred - ERROR_UNKNOWN = 0 + # An unknown error occurred + ERROR_UNKNOWN = 0 - # The database could not be loaded - ERROR_CANNOTLOADDATABASE = 1 + # The database could not be loaded + ERROR_CANNOTLOADDATABASE = 1 - def __init__(self, enumeration, message): - assert isinstance(enumeration, int) + def __init__(self, enumeration, message): + assert isinstance(enumeration, int) - if enumeration > 1: - raise Exception("Encountered undefined CompilationDatabase error " - "constant: %d. Please file a bug to have this " - "value supported." % enumeration) + if enumeration > 1: + raise Exception("Encountered undefined CompilationDatabase error " + "constant: %d. Please file a bug to have this " + "value supported." % enumeration) - self.cdb_error = enumeration - Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) + self.cdb_error = enumeration + Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) class CompileCommand(object): - """Represents the compile command used to build a file""" - def __init__(self, cmd, ccmds): - self.cmd = cmd - # Keep a reference to the originating CompileCommands - # to prevent garbage collection - self.ccmds = ccmds - - @property - def directory(self): - """Get the working directory for this CompileCommand""" - return conf.lib.clang_CompileCommand_getDirectory(self.cmd) - - @property - def filename(self): - """Get the working filename for this CompileCommand""" - return conf.lib.clang_CompileCommand_getFilename(self.cmd) - - @property - def arguments(self): - """ - Get an iterable object providing each argument in the - command line for the compiler invocation as a _CXString. - - Invariant : the first argument is the compiler executable - """ - length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) - for i in xrange(length): - yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) + """Represents the compile command used to build a file""" + def __init__(self, cmd, ccmds): + self.cmd = cmd + # Keep a reference to the originating CompileCommands + # to prevent garbage collection + self.ccmds = ccmds + + @property + def directory(self): + """Get the working directory for this CompileCommand""" + return conf.lib.clang_CompileCommand_getDirectory(self.cmd) + + @property + def filename(self): + """Get the working filename for this CompileCommand""" + return conf.lib.clang_CompileCommand_getFilename(self.cmd) + + @property + def arguments(self): + """ + Get an iterable object providing each argument in the + command line for the compiler invocation as a _CXString. + + Invariant : the first argument is the compiler executable + """ + length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) + for i in xrange(length): + yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) class CompileCommands(object): - """ - CompileCommands is an iterable object containing all CompileCommand - that can be used for building a specific file. - """ - def __init__(self, ccmds): - self.ccmds = ccmds - - def __del__(self): - conf.lib.clang_CompileCommands_dispose(self.ccmds) - - def __len__(self): - return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) - - def __getitem__(self, i): - cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) - if not cc: - raise IndexError - return CompileCommand(cc, self) - - @staticmethod - def from_result(res, fn, args): - if not res: - return None - return CompileCommands(res) + """ + CompileCommands is an iterable object containing all CompileCommand + that can be used for building a specific file. + """ + def __init__(self, ccmds): + self.ccmds = ccmds + + def __del__(self): + conf.lib.clang_CompileCommands_dispose(self.ccmds) + + def __len__(self): + return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) + + def __getitem__(self, i): + cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) + if not cc: + raise IndexError + return CompileCommand(cc, self) + + @staticmethod + def from_result(res, fn, args): + if not res: + return None + return CompileCommands(res) class CompilationDatabase(ClangObject): - """ - The CompilationDatabase is a wrapper class around - clang::tooling::CompilationDatabase - - It enables querying how a specific source file can be built. - """ - - def __del__(self): - conf.lib.clang_CompilationDatabase_dispose(self) - - @staticmethod - def from_result(res, fn, args): - if not res: - raise CompilationDatabaseError(0, - "CompilationDatabase loading failed") - return CompilationDatabase(res) - - @staticmethod - def fromDirectory(buildDir): - """Builds a CompilationDatabase from the database found in buildDir""" - errorCode = c_uint() - try: - cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir, - byref(errorCode)) - except CompilationDatabaseError as e: - raise CompilationDatabaseError(int(errorCode.value), - "CompilationDatabase loading failed") - return cdb - - def getCompileCommands(self, filename): - """ - Get an iterable object providing all the CompileCommands available to - build filename. Returns None if filename is not found in the database. - """ - return conf.lib.clang_CompilationDatabase_getCompileCommands(self, - filename) - - def getAllCompileCommands(self): - """ - Get an iterable object providing all the CompileCommands available from - the database. - """ - return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self) + """ + The CompilationDatabase is a wrapper class around + clang::tooling::CompilationDatabase + + It enables querying how a specific source file can be built. + """ + + def __del__(self): + conf.lib.clang_CompilationDatabase_dispose(self) + + @staticmethod + def from_result(res, fn, args): + if not res: + raise CompilationDatabaseError(0, + "CompilationDatabase loading failed") + return CompilationDatabase(res) + + @staticmethod + def fromDirectory(buildDir): + """Builds a CompilationDatabase from the database found in buildDir""" + errorCode = c_uint() + try: + cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir, + byref(errorCode)) + except CompilationDatabaseError as e: + raise CompilationDatabaseError(int(errorCode.value), + "CompilationDatabase loading failed") + return cdb + + def getCompileCommands(self, filename): + """ + Get an iterable object providing all the CompileCommands available to + build filename. Returns None if filename is not found in the database. + """ + return conf.lib.clang_CompilationDatabase_getCompileCommands(self, + filename) + + def getAllCompileCommands(self): + """ + Get an iterable object providing all the CompileCommands available from + the database. + """ + return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self) class Token(Structure): - """Represents a single token from the preprocessor. + """Represents a single token from the preprocessor. - Tokens are effectively segments of source code. Source code is first parsed - into tokens before being converted into the AST and Cursors. + Tokens are effectively segments of source code. Source code is first parsed + into tokens before being converted into the AST and Cursors. - Tokens are obtained from parsed TranslationUnit instances. You currently - can't create tokens manually. - """ - _fields_ = [ - ('int_data', c_uint * 4), - ('ptr_data', c_void_p) - ] + Tokens are obtained from parsed TranslationUnit instances. You currently + can't create tokens manually. + """ + _fields_ = [ + ('int_data', c_uint * 4), + ('ptr_data', c_void_p) + ] - @property - def spelling(self): - """The spelling of this token. + @property + def spelling(self): + """The spelling of this token. - This is the textual representation of the token in source. - """ - return conf.lib.clang_getTokenSpelling(self._tu, self) + This is the textual representation of the token in source. + """ + return conf.lib.clang_getTokenSpelling(self._tu, self) - @property - def kind(self): - """Obtain the TokenKind of the current token.""" - return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) + @property + def kind(self): + """Obtain the TokenKind of the current token.""" + return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) - @property - def location(self): - """The SourceLocation this Token occurs at.""" - return conf.lib.clang_getTokenLocation(self._tu, self) + @property + def location(self): + """The SourceLocation this Token occurs at.""" + return conf.lib.clang_getTokenLocation(self._tu, self) - @property - def extent(self): - """The SourceRange this Token occupies.""" - return conf.lib.clang_getTokenExtent(self._tu, self) + @property + def extent(self): + """The SourceRange this Token occupies.""" + return conf.lib.clang_getTokenExtent(self._tu, self) - @property - def cursor(self): - """The Cursor this Token corresponds to.""" - cursor = Cursor() - cursor._tu = self._tu + @property + def cursor(self): + """The Cursor this Token corresponds to.""" + cursor = Cursor() + cursor._tu = self._tu - conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) + conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) - return cursor + return cursor # Now comes the plumbing to hook up the C library. # Register callback types in common container. callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, - POINTER(SourceLocation), c_uint, py_object) + POINTER(SourceLocation), c_uint, py_object) callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object) @@ -3711,7 +3725,7 @@ def cursor(self): ("clang_getInstantiationLocation", [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), - POINTER(c_uint)]), + POINTER(c_uint)]), ("clang_getLocation", [TranslationUnit, File, c_uint, c_uint], @@ -4021,167 +4035,175 @@ def cursor(self): ] class LibclangError(Exception): - def __init__(self, message): - self.m = message + def __init__(self, message): + self.m = message - def __str__(self): - return self.m + def __str__(self): + return self.m def register_function(lib, item, ignore_errors): - # A function may not exist, if these bindings are used with an older or - # incompatible version of libclang.so. - try: - func = getattr(lib, item[0]) - except AttributeError as e: - msg = str(e) + ". Please ensure that your python bindings are "\ - "compatible with your libclang.so version." - if ignore_errors: - return - raise LibclangError(msg) - - if len(item) >= 2: - func.argtypes = item[1] - - if len(item) >= 3: - func.restype = item[2] - - if len(item) == 4: - func.errcheck = item[3] + # A function may not exist, if these bindings are used with an older or + # incompatible version of libclang.so. + try: + func = getattr(lib, item[0]) + except AttributeError as e: + msg = str(e) + ". Please ensure that your python bindings are "\ + "compatible with your libclang.so version." + if ignore_errors: + return + raise LibclangError(msg) + + if len(item) >= 2: + func.argtypes = item[1] + + if len(item) >= 3: + func.restype = item[2] + + if len(item) == 4: + func.errcheck = item[3] def register_functions(lib, ignore_errors): - """Register function prototypes with a libclang library instance. + """Register function prototypes with a libclang library instance. - This must be called as part of library instantiation so Python knows how - to call out to the shared library. - """ + This must be called as part of library instantiation so Python knows how + to call out to the shared library. + """ - def register(item): - return register_function(lib, item, ignore_errors) + def register(item): + return register_function(lib, item, ignore_errors) - for f in functionList: - register(f) + for f in functionList: + register(f) class Config: - library_path = None - library_file = None - compatibility_check = True - loaded = False - - @staticmethod - def set_library_path(path): - """Set the path in which to search for libclang""" - if Config.loaded: - raise Exception("library path must be set before before using " \ - "any other functionalities in libclang.") - - Config.library_path = path - - @staticmethod - def set_library_file(filename): - """Set the exact location of libclang""" - if Config.loaded: - raise Exception("library file must be set before before using " \ - "any other functionalities in libclang.") - - Config.library_file = filename - - @staticmethod - def set_compatibility_check(check_status): - """ Perform compatibility check when loading libclang - - The python bindings are only tested and evaluated with the version of - libclang they are provided with. To ensure correct behavior a (limited) - compatibility check is performed when loading the bindings. This check - will throw an exception, as soon as it fails. - - In case these bindings are used with an older version of libclang, parts - that have been stable between releases may still work. Users of the - python bindings can disable the compatibility check. This will cause - the python bindings to load, even though they are written for a newer - version of libclang. Failures now arise if unsupported or incompatible - features are accessed. The user is required to test themselves if the - features they are using are available and compatible between different - libclang versions. - """ - if Config.loaded: - raise Exception("compatibility_check must be set before before " \ - "using any other functionalities in libclang.") - - Config.compatibility_check = check_status - - @CachedProperty - def lib(self): - lib = self.get_cindex_library() - register_functions(lib, not Config.compatibility_check) - Config.loaded = True - return lib - - def get_filename(self): - if Config.library_file: - return Config.library_file - - import platform - name = platform.system() - - if name == 'Darwin': - file = 'libclang.dylib' - elif name == 'Windows': - file = 'libclang.dll' - else: - file = 'libclang.so' - - if Config.library_path: - file = Config.library_path + '/' + file - - return file - - def get_cindex_library(self): - try: - library = cdll.LoadLibrary(self.get_filename()) - except OSError as e: - msg = str(e) + ". To provide a path to libclang use " \ - "Config.set_library_path() or " \ - "Config.set_library_file()." - raise LibclangError(msg) - - return library - - def function_exists(self, name): - try: - getattr(self.lib, name) - except AttributeError: - return False - - return True + library_path = None + library_file = None + compatibility_check = True + loaded = False + _lib=None + + @staticmethod + def set_library_path(path): + """Set the path in which to search for libclang""" + if Config.loaded: + raise Exception("library path must be set before before using " \ + "any other functionalities in libclang.") + + Config.library_path = path + + @staticmethod + def set_library_file(filename): + """Set the exact location of libclang""" + if Config.loaded: + raise Exception("library file must be set before before using " \ + "any other functionalities in libclang.") + + Config.library_file = filename + + @staticmethod + def set_compatibility_check(check_status): + """ Perform compatibility check when loading libclang + + The python bindings are only tested and evaluated with the version of + libclang they are provided with. To ensure correct behavior a (limited) + compatibility check is performed when loading the bindings. This check + will throw an exception, as soon as it fails. + + In case these bindings are used with an older version of libclang, parts + that have been stable between releases may still work. Users of the + python bindings can disable the compatibility check. This will cause + the python bindings to load, even though they are written for a newer + version of libclang. Failures now arise if unsupported or incompatible + features are accessed. The user is required to test themselves if the + features they are using are available and compatible between different + libclang versions. + """ + if Config.loaded: + raise Exception("compatibility_check must be set before before " \ + "using any other functionalities in libclang.") + + Config.compatibility_check = check_status + + def unload_lib(self): + _lib=None + + # was @CachedProperty but we need to reload in case of a crash. + @property + def lib(self): + if self._lib: + return self._lib + self._lib = self.get_cindex_library() + register_functions(self._lib, not Config.compatibility_check) + Config.loaded = True + return self._lib + + def get_filename(self): + if Config.library_file: + return Config.library_file + + import platform + name = platform.system() + + if name == 'Darwin': + file = 'libclang.dylib' + elif name == 'Windows': + file = 'libclang.dll' + else: + file = 'libclang.so' + + if Config.library_path: + file = Config.library_path + '/' + file + + return file + + def get_cindex_library(self): + try: + fn=self.get_filename() + library = cdll.LoadLibrary(fn) + except OSError as e: + msg = str(e) + ". To provide a path to libclang use " \ + "Config.set_library_path() or " \ + "Config.set_library_file()." + raise LibclangError(msg) + + return library + + def function_exists(self, name): + try: + getattr(self.lib, name) + except AttributeError: + return False + + return True def register_enumerations(): - for name, value in enumerations.TokenKinds: - TokenKind.register(value, name) + for name, value in enumerations.TokenKinds: + TokenKind.register(value, name) conf = Config() register_enumerations() __all__ = [ - 'AvailabilityKind', - 'Config', - 'CodeCompletionResults', - 'CompilationDatabase', - 'CompileCommands', - 'CompileCommand', - 'CursorKind', - 'Cursor', - 'Diagnostic', - 'File', - 'FixIt', - 'Index', - 'LinkageKind', - 'SourceLocation', - 'SourceRange', - 'TLSKind', - 'TokenKind', - 'Token', - 'TranslationUnitLoadError', - 'TranslationUnit', - 'TypeKind', - 'Type', + 'AvailabilityKind', + 'Config', + 'CodeCompletionResults', + 'CompilationDatabase', + 'CompileCommands', + 'CompileCommand', + 'CursorKind', + 'Cursor', + 'Diagnostic', + 'File', + 'FixIt', + 'Index', + 'LinkageKind', + 'SourceLocation', + 'SourceRange', + 'TLSKind', + 'TokenKind', + 'Token', + 'TranslationUnitLoadError', + 'TranslationUnit', + 'TypeKind', + 'Type', ] diff --git a/cldoc/clang/enumerations.py b/cldoc/clang/enumerations.py index a86a48a..03aad0b 100644 --- a/cldoc/clang/enumerations.py +++ b/cldoc/clang/enumerations.py @@ -1,6 +1,6 @@ #===- enumerations.py - Python Enumerations ------------------*- python -*--===# # -# The LLVM Compiler Infrastructure +# The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. @@ -24,11 +24,11 @@ # Maps to CXTokenKind. Note that libclang maintains a separate set of token # enumerations from the C++ API. TokenKinds = [ - ('PUNCTUATION', 0), - ('KEYWORD', 1), - ('IDENTIFIER', 2), - ('LITERAL', 3), - ('COMMENT', 4), + ('PUNCTUATION', 0), + ('KEYWORD', 1), + ('IDENTIFIER', 2), + ('LITERAL', 3), + ('COMMENT', 4), ] __all__ = ['TokenKinds'] diff --git a/cldoc/cmdgenerate.py b/cldoc/cmdgenerate.py index cb44df9..c900f97 100644 --- a/cldoc/cmdgenerate.py +++ b/cldoc/cmdgenerate.py @@ -14,121 +14,191 @@ import sys, os, argparse, tempfile, subprocess, shutil -from . import fs, staticsite +from . import fs from . import log +import glob +import time +import re def run_generate(t, opts): - if opts.type != 'html' and opts.type != 'xml': - return - - from . import generators - - generator = generators.Xml(t, opts) - - if opts.type == 'html' and opts.static: - baseout = fs.fs.mkdtemp() - else: - baseout = opts.output - - xmlout = os.path.join(baseout, 'xml') - generator.generate(xmlout) - - if opts.type == 'html': - generators.Html(t).generate(baseout, opts.static, opts.custom_js, opts.custom_css) - - if opts.static: - staticsite.generate(baseout, opts) + if opts.type != 'md': + return + + from . import generators + + baseout = opts.output + + if opts.type == 'md': + generator_md = generators.Md(t, opts) + generator_md.generate(baseout) + if opts.post!=None and opts.post != '': + args=opts.post.split(' ') + process = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) + for line in process.stdout: + sys.stdout.write(str(line.decode('UTF-8'))) + if process.stderr: + for line in process.stderr: + sys.stdout.write(str(line.decode('UTF-8'))) + #ret=subprocess.call(args,shell=True) + process.wait() + if process.returncode!=0: + sys.stderr.write('Error: failed to run post process '+opts.post+'\n') + sys.exit(1) def run(args): - try: - sep = args.index('--') - except ValueError: - if not '--help' in args: - sys.stderr.write('Please use: cldoc generate [CXXFLAGS] -- [OPTIONS] [FILES]\n') - sys.exit(1) - else: - sep = -1 - - parser = argparse.ArgumentParser(description='clang based documentation generator.', - usage='%(prog)s generate [CXXFLAGS] -- [OPTIONS] [FILES]') - - parser.add_argument('--quiet', default=False, action='store_const', const=True, - help='be quiet about it') - - parser.add_argument('--loglevel', default='error', metavar='LEVEL', - help='specify the logevel (error, warning, info)') - - parser.add_argument('--report', default=False, - action='store_const', const=True, help='report documentation coverage and errors') - - parser.add_argument('--output', default=None, metavar='DIR', - help='specify the output directory') - - parser.add_argument('--language', default='c++', metavar='LANGUAGE', - help='specify the default parse language (c++, c or objc)') - - parser.add_argument('--type', default='html', metavar='TYPE', - help='specify the type of output (html or xml, default html)') - - parser.add_argument('--merge', default=[], metavar='FILES', action='append', - help='specify additional description files to merge into the documentation') - - parser.add_argument('--merge-filter', default=None, metavar='FILTER', - help='specify program to pass merged description files through') - - parser.add_argument('--basedir', default=None, metavar='DIR', - help='the project base directory') - - parser.add_argument('--static', default=False, action='store_const', const=True, - help='generate a static website (only for when --output is html, requires globally installed cldoc-static via npm)') - - parser.add_argument('--custom-js', default=[], metavar='FILES', action='append', - help='specify additional javascript files to be merged into the html (only for when --output is html)') - - parser.add_argument('--custom-css', default=[], metavar='FILES', action='append', - help='specify additional css files to be merged into the html (only for when --output is html)') - - parser.add_argument('files', nargs='+', help='files to parse') - - restargs = args[sep + 1:] - cxxflags = args[:sep] - - opts = parser.parse_args(restargs) - - if opts.quiet: - sys.stdout = open(os.devnull, 'w') - - log.setLevel(opts.loglevel) - - from . import tree - - if not opts.output: - sys.stderr.write("Please specify the output directory\n") - sys.exit(1) - - if opts.static and opts.type != 'html': - sys.stderr.write("The --static option can only be used with the html output format\n") - sys.exit(1) - - haslang = False - - for x in cxxflags: - if x.startswith('-x'): - haslang = True - - if not haslang: - cxxflags.append('-x') - cxxflags.append(opts.language) - - t = tree.Tree(opts.files, cxxflags) - - t.process() - - if opts.merge: - t.merge(opts.merge_filter, opts.merge) - - t.cross_ref() - - run_generate(t, opts) + genfile='' + try: + sep = args.index('--') + except ValueError: + if not '--help' in args: + genfile=args[0] + else: + sep = -1 + + if genfile!='': + try: + file = open(genfile,'r') + except: + sys.stderr.write('Please use: cldoc generate [CXXFLAGS] -- [OPTIONS] [FILES]\n') + sys.exit(1) + args_file =file.read().splitlines() + args=args_file+args[1:] + sep = args.index('--') + + for i in range(len(args)): + arg=args[i] + reg=re.compile('\$\{([a-zA-z0-9]+)}', re.IGNORECASE) + iterator=reg.finditer(arg) + for match in iterator: + sp=match.span() + envname=match[1] + env=os.environ.get(envname) + if env==None: + sys.stderr.write('Env var '+envname+' not found.\n') + sys.exit(1) + arg=arg[0:sp[0]]+env+arg[sp[1]:] + iterator=reg.finditer(arg) + args[i]=arg + + parser = argparse.ArgumentParser(description='clang based documentation generator.', + usage='%(prog)s generate [CXXFLAGS] -- [OPTIONS] [FILES]') + + parser.add_argument('--quiet', default=False, action='store_const', const=True, + help='be quiet about it') + + parser.add_argument('--loglevel', default='error', metavar='LEVEL', + help='specify the logevel (error, warning, info)') + + parser.add_argument('--report', default=False, + action='store_const', const=True, help='report documentation coverage and errors') + + parser.add_argument('--output', default=None, metavar='DIR', + help='specify the output directory') + + parser.add_argument('--md_output', default='', metavar='DIR', + help='specify the relative markdown generated files output directory') + + parser.add_argument('--language', default='c++', metavar='LANGUAGE', + help='specify the default parse language (c++, c or objc)') + + parser.add_argument('--type', default='html', metavar='TYPE', + help='specify the type of output (html or xml, default html)') + + parser.add_argument('--merge', default=[], metavar='FILES', action='append', + help='specify additional description files to merge into the documentation') + + parser.add_argument('--merge-filter', default=None, metavar='FILTER', + help='specify program to pass merged description files through') + + parser.add_argument('--basedir', default=None, metavar='DIR', + help='the project base directory') + + parser.add_argument('--static', default=False, action='store_const', const=True, + help='generate a static website (only for when --output is html, requires globally installed cldoc-static via npm)') + + parser.add_argument('--custom-js', default=[], metavar='FILES', action='append', + help='specify additional javascript files to be merged into the html (only for when --output is html)') + + parser.add_argument('--custom-css', default=[], metavar='FILES', action='append', + help='specify additional css files to be merged into the html (only for when --output is html)') + + parser.add_argument('--clean', default=None, metavar='CLEAN', + help='directory to clean before running') + + parser.add_argument('--strip', default=None, metavar='STRIP', + help='path to remove from filenames') + + parser.add_argument('--post', default=None, metavar='POST', + help='command to execute after completion') + + parser.add_argument('--image-destination', default='images', metavar='IMAGE_TARGET', + help='Folder to put images in under output dir.') + + parser.add_argument('--image-path', default=[], metavar='IMAGE_PATHS', action='append', + help='Source paths for images.') + + parser.add_argument('files', nargs='+', help='files to parse') + + restargs = args[sep + 1:] + cxxflags = args[:sep] + + opts = parser.parse_args(restargs) + newfiles=[] + for filepath in opts.files: + gfiles=glob.glob(filepath) + newfiles=newfiles+gfiles + opts.files=newfiles + if opts.quiet: + sys.stdout = open(os.devnull, 'w') + if opts.clean: + r = glob.glob(opts.clean+'/*') + for i in r: + if os.path.isdir(i): + try: + shutil.rmtree(i) + except: + sys.stderr.write('Warning: failed to delete '+i+'\n') + else: + os.remove(i) + + log.setLevel(opts.loglevel) + + from . import tree + + if opts.strip: + opts.strip=opts.strip.replace('\\','/') + opts.strip=opts.strip.replace('//','/') + + if not opts.output: + sys.stderr.write("Please specify the output directory\n") + sys.exit(1) + + if opts.static and opts.type != 'html': + sys.stderr.write("The --static option can only be used with the html output format\n") + sys.exit(1) + + haslang = False + + for x in cxxflags: + if x.startswith('-x'): + haslang = True + + if not haslang: + cxxflags.append('-x') + cxxflags.append(opts.language) + + t = tree.Tree(opts.files, cxxflags, opts) + + start = time.time() + t.process() + if opts.merge: + t.merge(opts.merge_filter, opts.merge) + t.cross_ref() + run_generate(t, opts) + end = time.time() + total=end - start + mins=int((total)/60.0) + secs=int(total-(mins*60)) + print("Took "+str(mins)+" minutes, "+str(secs)+" seconds") # vi:ts=4:et diff --git a/cldoc/cmdgir.py b/cldoc/cmdgir.py deleted file mode 100644 index 1925403..0000000 --- a/cldoc/cmdgir.py +++ /dev/null @@ -1,952 +0,0 @@ -# This file is part of cldoc. cldoc is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from __future__ import absolute_import - -import sys, argparse, re, os - -try: - from xml.etree import cElementTree as ElementTree -except: - from xml.etree import ElementTree - -from .clang import cindex - -from . import defdict - -from . import nodes -from . import generators -from . import comment -from . import example -from . import documentmerger -from . import utf8 - -def nsgtk(s): - return '{{{0}}}{1}'.format('http://www.gtk.org/introspection/core/1.0', s) - -def nsc(s): - return '{{{0}}}{1}'.format('http://www.gtk.org/introspection/c/1.0', s) - -def nsglib(s): - return '{{{0}}}{1}'.format('http://www.gtk.org/introspection/glib/1.0', s) - -def stripns(tag): - try: - pos = tag.index('}') - return tag[pos+1:] - except: - return tag - -class Interface(nodes.Class): - @property - def classname(self): - return '{http://jessevdk.github.com/cldoc/gobject/1.0}interface' - -class Class(nodes.Class): - def __init__(self, cursor, comment): - nodes.Class.__init__(self, cursor, comment) - - # Extract bases - for b in cursor.bases: - self.bases.append(nodes.Class.Base(b)) - - for i in cursor.implements: - self.implements.append(nodes.Class.Base(i)) - - @property - def classname(self): - return '{http://jessevdk.github.com/cldoc/gobject/1.0}class' - -class Property(nodes.Node): - def __init__(self, cursor, comment): - nodes.Node.__init__(self, cursor, comment) - - self.type = nodes.Type(cursor.type) - - @property - def classname(self): - return '{http://jessevdk.github.com/cldoc/gobject/1.0}property' - - @property - def props(self): - ret = nodes.Node.props.fget(self) - - mode = [] - - if not ('writable' in self.cursor.node.attrib and self.cursor.node.attrib['writable'] == '1'): - mode.append('readonly') - - if 'construct-only' in self.cursor.node.attrib and self.cursor.node.attrib['construct-only'] == '1': - mode.append('construct-only') - - if 'construct' in self.cursor.node.attrib and self.cursor.node.attrib['construct'] == '1': - mode.append('construct') - - if len(mode) > 0: - ret['mode'] = ",".join(mode) - - return ret - -class Boxed(nodes.Struct): - def __init__(self, cursor, comment): - nodes.Struct.__init__(self, cursor, comment) - - @property - def classname(self): - return '{http://jessevdk.github.com/cldoc/gobject/1.0}boxed' - - @property - def force_page(self): - return True - -class GirComment(comment.Comment): - hashref = re.compile('#([a-z_][a-z0-9_]*)', re.I) - emph = re.compile('(.*?)', re.I) - title = re.compile('(.*?)', re.I) - refsect2 = re.compile('(]*>|)\n?', re.I) - varref = re.compile('@([a-z][a-z0-9_]*)', re.I) - constref = re.compile('%([a-z_][a-z0-9_]*)', re.I) - proglisting = re.compile('\s*\s*(.*?)\s*\s*', re.I | re.M) - - def __init__(self, cursor): - doc = cursor.node.find(nsgtk('doc')) - - if not doc is None: - text = doc.text - else: - text = '' - - text = self.subst_format(text) - - brieftext = text - doctext = '' - - try: - firstdot = text.index('.') - - try: - firstnl = text.index("\n") - except: - firstnl = firstdot - - if firstnl < firstdot: - firstdot = firstnl - 1 - - nextnonsp = firstdot + 1 - - while nextnonsp < len(text) and text[nextnonsp] != '\n' and not text[nextnonsp].isspace(): - nextnonsp += 1 - - if nextnonsp != len(text): - # Replicate brief and non brief... - # Insert newline just after . - brieftext = text[:firstdot] - doctext = text - except: - pass - - if cursor.typename in ['method', 'function', 'virtual-method', 'constructor']: - # Assemble function argument comments and return value comment - preat = [] - postat = [] - - for param in cursor.children: - paramdoc = param.node.find(nsgtk('doc')) - - if not paramdoc is None: - paramdoc = self.subst_format(paramdoc.text) - else: - paramdoc = '*documentation missing...*' - - preat.append('@{0} {1}'.format(param.spelling, paramdoc.replace('\n', ' '))) - - return_node = cursor.node.find(nsgtk('return-value')) - - if not return_node is None and cursor.type.get_result().spelling != 'void': - doc = return_node.find(nsgtk('doc')) - - if not doc is None: - postat.append('@return {0}'.format(self.subst_format(doc.text).replace('\n', ' '))) - else: - postat.append('@return *documentation missing...*') - - if len(cursor.children) > 0: - preat.append('') - - if len(doctext) > 0: - preat.append('') - - if brieftext == '': - brieftext = '*documentation missing...*' - - text = brieftext.replace('\n', ' ').rstrip() + "\n" + "\n".join(preat) + doctext - - if len(postat) != 0: - text += '\n\n' + '\n'.join(postat) - else: - if doctext != '': - text = brieftext + "\n\n" + doctext - else: - text = brieftext.replace("\n", ' ') - - comment.Comment.__init__(self, text, None) - - def subst_format(self, text): - text = GirComment.hashref.sub(lambda x: '<{0}>'.format(x.group(1)), text) - text = GirComment.varref.sub(lambda x: '<{0}>'.format(x.group(1)), text) - text = GirComment.constref.sub(lambda x: '`{0}`'.format(x.group(1)), text) - text = GirComment.emph.sub(lambda x: '*{0}*'.format(x.group(1)), text) - text = GirComment.title.sub(lambda x: '## {0}'.format(x.group(1)), text) - text = GirComment.refsect2.sub(lambda x: '', text) - text = GirComment.proglisting.sub(lambda x: ' [code]\n {0}\n'.format(x.group(1).replace('\n', '\n ')), text) - - return text - -class GirType: - builtins = [ - 'utf8', - 'gchar', - 'gint', - 'gint8', - 'gint16', - 'gint32', - 'gint64', - 'guint', - 'guint8', - 'guint16', - 'guint32', - 'guint64', - 'gfloat', - 'gdouble', - 'gpointer', - 'gsize', - 'gboolean', - 'none' - ]; - - def __init__(self, node): - self.node = node - self.kind = cindex.TypeKind.UNEXPOSED - self.const_qualified = False - - self.is_out = False - self.transfer_ownership = 'none' - self.allow_none = False - - aname = nsc('type') - - if aname in self.node.attrib: - self.spelling = self.node.attrib[aname] - else: - self.spelling = '' - - self._extract_const() - self._extract_kind() - self.declaration = None - - retval = self.node.find(nsgtk('return-value')) - - if not retval is None: - self.return_type = GirCursor(retval).type - - if 'transfer-ownership' in retval.attrib: - self.return_type.transfer_ownership = retval.attrib['transfer-ownership'] - - if 'allow-none' in retval.attrib: - self.return_type.allow_none = retval.attrib['allow-none'] == '1' - else: - self.return_type = None - - def is_builtin(self): - return self.spelling in GirType.builtins - - def _extract_const(self): - prefix = 'const ' - - if self.spelling.startswith(prefix): - self.const_qualified = True - self.spelling = self.spelling[len(prefix):] - - def _extract_kind(self): - if self.spelling == '': - return - - if self.spelling.endswith('*'): - self.kind = cindex.TypeKind.POINTER - return - - for k in nodes.Type.namemap: - if nodes.Type.namemap[k] == self.spelling: - self.kind = k - break - - def get_pointee(self): - return GirTypePointer(self) - - def get_result(self): - return self.return_type - - def get_canonical(self): - return self - - def get_declaration(self): - return self.declaration - - def is_const_qualified(self): - return self.const_qualified - - def resolve_refs(self, resolver): - if not self.return_type is None: - self.return_type.resolve_refs(resolver) - - if not self.declaration is None: - return - - if 'name' in self.node.attrib: - name = self.node.attrib['name'] - self.declaration = resolver(name) - - if self.spelling == '' and not self.declaration is None: - self.spelling = self.declaration.spelling - - if self.declaration.typename in ['record', 'class', 'interface']: - self.spelling += ' *' - self.kind = cindex.TypeKind.POINTER - - elif self.spelling == '' and name in GirType.builtins: - if name == 'utf8': - self.spelling = 'gchar *' - elif name == 'none': - self.spelling = 'void' - else: - self.spelling = name - -class GirTypePointer(GirType): - def __init__(self, tp): - self.node = tp.node - self.pointer_type = tp - self.spelling = tp.spelling[:-1] - self.kind = cindex.TypeKind.UNEXPOSED - self.const_qualified = False - - self._extract_const() - self._extract_kind() - - def get_declaration(self): - return self.pointer_type.get_declaration() - -class GirCursor: - kindmap = { - 'parameter': cindex.CursorKind.PARM_DECL - } - - global_gerror_param = None - - def __init__(self, node): - self.node = node - self.typename = stripns(self.node.tag) - self.children = [] - self.parent = None - self.bases = None - self.implements = None - - if 'introspectable' in node.attrib: - self.introspectable = (node.attrib['introspectable'] != '0') - else: - self.introspectable = True - - self.type = self._extract_type() - self.kind = self._extract_kind() - - self._virtual_param = None - - if self._is_object_type(): - self._create_virtual_param() - - if self.typename == 'member': - self.enum_value = node.attrib['value'] - - self._extract_children() - - def _extract_kind(self): - if self.typename in GirCursor.kindmap: - return GirCursor.kindmap[self.typename] - else: - return cindex.CursorKind.UNEXPOSED_DECL - - def _extract_type(self): - if self.typename == 'type': - return GirType(self.node) - - t = self.node.find(nsgtk('type')) - - if not t is None: - retval = GirType(t) - - if 'direction' in self.node.attrib: - retval.is_out = self.node.attrib['direction'] == 'out' - - if 'transfer-ownership' in self.node.attrib and not retval.is_out: - retval.transfer_ownership = self.node.attrib['transfer-ownership'] - - if 'allow-none' in self.node.attrib: - retval.allow_none = self.node.attrib['allow-none'] == '1' - - return retval - - va = self.node.find(nsgtk('varargs')) - - if not va is None: - return GirType(va) - - ar = self.node.find(nsgtk('array')) - - if not ar is None: - return GirType(ar) - - ret = GirType(self.node) - ret.declaration = self - - return ret - - def _is_object_type(self): - return self.typename in ['class', 'interface'] or \ - (self.typename == 'record' and nsglib('get-type') in self.node.attrib) - - def _create_virtual_param(self): - # Make virtual first parameter representing pointer to object - param = ElementTree.Element(nsgtk('parameter')) - - param.attrib['name'] = 'self' - param.attrib['transfer-ownership'] = 'none' - - ntp = nsc('type') - - tp = ElementTree.Element(nsgtk('type')) - tp.attrib['name'] = self.node.attrib['name'] - tp.attrib[ntp] = self.node.attrib[ntp] + '*' - - doc = ElementTree.Element(nsgtk('doc')) - doc.text = 'a <{0}>.'.format(self.node.attrib[ntp]) - - param.append(doc) - param.append(tp) - - self._virtual_param = param - - def _setup_first_param(self, method): - method.children.insert(0, GirCursor(self._virtual_param)) - - def _make_gerror_param(self): - if not GirCursor.global_gerror_param is None: - return GirCursor.global_gerror_param - - param = ElementTree.Element(nsgtk('parameter')) - - param.attrib['name'] = 'error' - param.attrib['transfer-ownership'] = 'none' - param.attrib['allow-none'] = '1' - - tp = ElementTree.Element(nsgtk('type')) - - tp.attrib['name'] = 'Error' - tp.attrib[nsc('type')] = 'GError **' - - doc = ElementTree.Element(nsgtk('doc')) - doc.text = 'a #GError.' - - param.append(doc) - param.append(tp) - - GirCursor.global_gerror_param = param - return param - - def _extract_children(self): - children = [] - - if self.typename in ['function', 'method', 'virtual-method', 'constructor']: - children = list(self.node.iterfind(nsgtk('parameters') + '/' + nsgtk('parameter'))) - - if 'throws' in self.node.attrib and self.node.attrib['throws'] == '1': - children.append(self._make_gerror_param()) - - elif self.typename in ['enumeration', 'bitfield']: - children = self.node.iterfind(nsgtk('member')) - elif self.typename in ['record', 'class', 'interface']: - self.bases = [] - self.implements = [] - - def childgen(): - childtypes = ['function', 'method', 'constructor', 'virtual-method', 'property', 'field'] - - for child in self.node: - if stripns(child.tag) in childtypes: - yield child - - children = childgen() - - for child in children: - cursor = GirCursor(child) - - if not self._virtual_param is None and \ - cursor.typename == 'method' or cursor.typename == 'virtual-method': - self._setup_first_param(cursor) - - cursor.parent = self - self.children.append(cursor) - - @property - def displayname(self): - return self.name - - @property - def semantic_parent(self): - return self.parent - - @property - def spelling(self): - if self.typename in ['function', 'method', 'member', 'constructor']: - n = nsc('identifier') - elif self.typename in ['parameter', 'field', 'property']: - n = 'name' - else: - n = nsc('type') - - if n in self.node.attrib: - return self.node.attrib[n] - else: - return '' - - def is_static_method(self): - return False - - def is_virtual_method(self): - return self.typename == 'virtual-method' - - def is_definition(self): - return True - - @property - def name(self): - return self.spelling - - @property - def refname(self): - if nsglib('type-name') in self.node.attrib and 'name' in self.node.attrib: - return self.node.attrib['name'] - else: - return None - - @property - def extent(self): - return None - - @property - def location(self): - return None - - def get_children(self): - return self.children - - def _add_base(self, b): - if not b is None: - self.bases.append(b) - - def _add_implements(self, i): - if not i is None: - self.implements.append(i) - - def get_usr(self): - return self.spelling - - def resolve_refs(self, resolver): - # Resolve things like types and stuff - if not self.type is None: - self.type.resolve_refs(resolver) - - for child in self.children: - child.resolve_refs(resolver) - - # What about, like, baseclasses... - if self.typename in ['class', 'interface']: - if 'parent' in self.node.attrib: - self._add_base(resolver(self.node.attrib['parent'])) - - for implements in self.node.iterfind(nsgtk('implements')): - self._add_implements(resolver(implements.attrib['name'])) - -class GirTree(documentmerger.DocumentMerger): - def __init__(self, category=None): - self.mapping = { - 'function': self.parse_function, - 'class': self.parse_class, - 'record': self.parse_record, - 'interface': self.parse_interface, - 'enumeration': self.parse_enumeration, - 'callback': self.parse_callback, - 'bitfield': self.parse_enumeration, - 'virtual-method': self.parse_virtual_method, - 'method': self.parse_method, - 'constructor': self.parse_constructor, - 'property': self.parse_property, - 'signal': self.parse_signal, - 'field': self.parse_field, - 'doc': None, - 'implements': None, - 'prerequisite': None, - } - - self.category_to_node = defdict.Defdict() - - self.root = nodes.Root() - self.namespaces = {} - self.processed = {} - self.map_id_to_cusor = {} - self.cursor_to_node = {} - self.exported_namespaces = [] - self.usr_to_node = defdict.Defdict() - self.qid_to_node = defdict.Defdict() - self.all_nodes = [] - - self.usr_to_node[None] = self.root - self.qid_to_node[None] = self.root - - if not category is None: - self.category = self.add_categories([category]) - else: - self.category = None - - if not self.category is None: - self.root_node = self.category - else: - self.root_node = self.root - - def match_ref(self, child, name): - if isinstance(name, utf8.string): - return name == child.name - else: - return name.match(child.name) - - def find_ref(self, node, name, goup): - if node is None: - return [] - - ret = [] - - for child in node.resolve_nodes: - if self.match_ref(child, name): - ret.append(child) - - if goup and len(ret) == 0: - return self.find_ref(node.parent, name, True) - else: - return ret - - def cross_ref(self, node=None): - if node is None: - node = self.root - - if not node.comment is None: - node.comment.resolve_refs(self.find_ref, node) - - for child in node.children: - self.cross_ref(child) - - self.markup_code() - - def parse_function(self, cursor): - return nodes.Function(cursor, GirComment(cursor)) - - def parse_struct_children(self, ret): - for child in ret.cursor.children: - c = self.parse_cursor(child) - - if not c is None: - ret.append(c) - - def parse_class(self, cursor): - ret = Class(cursor, GirComment(cursor)) - - ret.typedef = nodes.Typedef(cursor, None) - self.parse_struct_children(ret) - - return ret - - def parse_signal(self, node): - # TODO - return None - - def parse_field(self, cursor): - if 'private' in cursor.node.attrib and cursor.node.attrib['private'] == '1': - return None - - return nodes.Field(cursor, GirComment(cursor)) - - def parse_constructor(self, cursor): - return nodes.Function(cursor, GirComment(cursor)) - - def parse_virtual_method(self, node): - # TODO - return None - - def parse_method(self, cursor): - return nodes.Function(cursor, GirComment(cursor)) - - def parse_property(self, cursor): - return Property(cursor, GirComment(cursor)) - - def parse_boxed(self, cursor): - ret = Boxed(cursor, GirComment(cursor)) - ret.typedef = nodes.Typedef(cursor, None) - - self.parse_struct_children(ret) - return ret - - def parse_record(self, cursor): - if nsglib('is-gtype-struct-for') in cursor.node.attrib: - return None - - if 'disguised' in cursor.node.attrib and cursor.node.attrib['disguised'] == '1': - return None - - if nsglib('get-type') in cursor.node.attrib: - return self.parse_boxed(cursor) - - ret = nodes.Struct(cursor, GirComment(cursor)) - ret.typedef = nodes.Typedef(cursor, None) - - self.parse_struct_children(ret) - - return ret - - def parse_interface(self, cursor): - ret = Interface(cursor, GirComment(cursor)) - self.parse_struct_children(ret) - - return ret - - def parse_enumeration(self, cursor): - ret = nodes.Enum(cursor, GirComment(cursor)) - - # All enums are typedefs - ret.typedef = nodes.Typedef(cursor, None) - - for member in cursor.children: - ret.append(nodes.EnumValue(member, GirComment(member))) - - return ret - - def parse_callback(self, cursor): - pass - - def parse_cursor(self, cursor): - if not cursor.introspectable: - return None - - fn = self.mapping[cursor.typename] - - if not fn is None: - ret = fn(cursor) - - if not ret is None: - self.cursor_to_node[cursor] = ret - self.all_nodes.append(ret) - - return ret - else: - return None - - def lookup_gir(self, ns, version): - dirs = os.getenv('XDG_DATA_DIRS') - - if dirs is None: - dirs = ['/usr/local/share', '/usr/share'] - else: - dirs = dirs.split(os.pathsep) - - for d in dirs: - fname = os.path.join(d, 'gir-1.0', "{0}-{1}.gir".format(ns, version)) - - if os.path.exists(fname): - return fname - - return None - - def gir_split(self, filename): - name, _ = os.path.splitext(os.path.basename(filename)) - return name.split('-', 2) - - def add_gir(self, filename, included=False): - ns, version = self.gir_split(filename) - - if (ns, version) in self.processed: - return - - tree = ElementTree.parse(filename) - repository = tree.getroot() - - self.processed[(ns, version)] = tree - - # First process includes - for include in repository.iterfind(nsgtk('include')): - incname = include.attrib['name'] - incversion = include.attrib['version'] - - filename = self.lookup_gir(incname, incversion) - - if filename is None: - sys.stderr.write('Could not find include `{0}-{1}\'\n'.format(incname, incversion)) - sys.exit(1) - - self.add_gir(filename, True) - - # Then process cursors - ns = repository.find(nsgtk('namespace')) - nsname = ns.attrib['name'] - - cursors = [] - - for child in ns: - cursor = GirCursor(child) - refname = cursor.refname - - if not refname is None: - self.map_id_to_cusor[nsname + '.' + refname] = cursor - - cursors.append(cursor) - - self.namespaces[nsname] = cursors - - if not included: - self.exported_namespaces.append(nsname) - - def resolve_ref(self, ns): - def resolver(item): - item = item.rstrip('*') - - if item in GirType.builtins: - return None - - if not '.' in item: - item = ns + '.' + item - - if item in self.map_id_to_cusor: - return self.map_id_to_cusor[item] - else: - return None - - return resolver - - def parse(self): - # Resolve cursor references - for ns in self.namespaces: - for cursor in self.namespaces[ns]: - cursor.resolve_refs(self.resolve_ref(ns)) - - classes = {} - - for ns in self.exported_namespaces: - for cursor in self.namespaces[ns]: - node = self.parse_cursor(cursor) - - if not node is None: - self.root_node.append(node) - - if isinstance(node, Class) or isinstance(node, Interface): - classes[node.qid] = node - - for qid in classes: - classes[qid].resolve_bases(classes) - - for node in self.all_nodes: - self.qid_to_node[node.qid] = node - - def markup_code(self): - for node in self.all_nodes: - if node.comment is None: - continue - - if not node.comment.doc: - continue - - comps = node.comment.doc.components - - - for i in range(len(comps)): - component = comps[i] - - if not isinstance(component, comment.Comment.Example): - continue - - text = str(component) - - ex = example.Example() - ex.append(text) - - comps[i] = ex - -def run(args): - parser = argparse.ArgumentParser(description='clang based documentation generator.', - usage='%(prog)s gir --output DIR [OPTIONS] GIRFILE') - - parser.add_argument('--quiet', default=False, action='store_const', const=True, - help='be quiet about it') - - parser.add_argument('--report', default=False, - action='store_const', const=True, help='report documentation coverage and errors') - - parser.add_argument('--output', default=None, metavar='DIR', - help='specify the output directory') - - parser.add_argument('--type', default='html', metavar='TYPE', - help='specify the type of output (html or xml, default html)') - - parser.add_argument('--merge', default=[], metavar='FILES', action='append', - help='specify additional description files to merge into the documentation') - - parser.add_argument('--merge-filter', default=None, metavar='FILTER', - help='specify program to pass merged description files through') - - parser.add_argument('--static', default=False, action='store_const', const=True, - help='generate a static website (only for when --output is html)') - - parser.add_argument('--category', default=None, metavar='CATEGORY', - help='category in which to place all symbols') - - parser.add_argument('--custom-js', default=[], metavar='FILES', action='append', - help='specify additional javascript files to be merged into the html (only for when --output is html)') - - parser.add_argument('--custom-css', default=[], metavar='FILES', action='append', - help='specify additional css files to be merged into the html (only for when --output is html)') - - parser.add_argument('files', nargs='+', help='gir files to parse') - - opts = parser.parse_args(args) - - t = GirTree(opts.category) - - # Generate artificial tree - for f in opts.files: - t.add_gir(f) - - t.parse() - - if opts.merge: - t.merge(opts.merge_filter, opts.merge) - - t.cross_ref() - - from .cmdgenerate import run_generate - - run_generate(t, opts) - -# vi:ts=4:et diff --git a/cldoc/cmdinspect.py b/cldoc/cmdinspect.py deleted file mode 100644 index 4960461..0000000 --- a/cldoc/cmdinspect.py +++ /dev/null @@ -1,43 +0,0 @@ -# This file is part of cldoc. cldoc is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from __future__ import absolute_import - -import sys, argparse - -def run(args): - try: - sep = args.index('--') - except ValueError: - if not '--help' in args: - sys.stderr.write('Please use: cldoc inspect [CXXFLAGS] -- [OPTIONS] [FILES]\n') - sys.exit(1) - else: - sep = 0 - - parser = argparse.ArgumentParser(description='clang based documentation generator.', - usage='%(prog)s inspect [CXXFLAGS] -- [OPTIONS] DIRECTORY') - - parser.add_argument('files', nargs='*', help='files to parse') - - restargs = args[sep + 1:] - cxxflags = args[:sep] - - opts = parser.parse_args(restargs) - - from . import tree - from . import inspecttree - - t = tree.Tree(opts.files, cxxflags) - inspecttree.inspect(t) - -# vi:ts=4:et diff --git a/cldoc/cmdserve.py b/cldoc/cmdserve.py deleted file mode 100644 index 641c1ca..0000000 --- a/cldoc/cmdserve.py +++ /dev/null @@ -1,96 +0,0 @@ -# This file is part of cldoc. cldoc is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from __future__ import absolute_import - -import subprocess, threading, time, sys, argparse, os -import SimpleHTTPServer, SocketServer - -class Server(SocketServer.TCPServer): - allow_reuse_address = True - -def handler_bind(directory): - class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): - def end_headers(self): - self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate') - self.send_header('Pragma', 'no-cache') - self.send_header('Expires', '0') - - SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self) - - def translate_path(self, path): - while path.startswith('/'): - path = path[1:] - - path = os.path.join(directory, path) - return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self, path) - - def log_message(self, format, *args): - pass - - return Handler - -class SocketThread(threading.Thread): - def __init__(self, directory, host): - threading.Thread.__init__(self) - - if not ':' in host: - self.host = host - self.port = 6060 - else: - self.host, port = host.split(':') - self.port = int(port) - - self.httpd = Server((self.host, self.port), handler_bind(directory)) - - def shutdown(self): - self.httpd.shutdown() - self.httpd.server_close() - - def run(self): - self.httpd.serve_forever() - -def run(args): - parser = argparse.ArgumentParser(description='clang based documentation generator.', - usage='%(prog)s serve [OPTIONS] [DIRECTORY]') - - parser.add_argument('--address', default=':6060', metavar='HOST:PORT', - help='address (host:port) on which to serve documentation') - - parser.add_argument('directory', nargs='?', help='directory to serve', default='.') - - opts = parser.parse_args(args) - - t = SocketThread(opts.directory, opts.address) - t.start() - - dn = open(os.devnull, 'w') - - if t.host == '': - url = 'http://localhost:{0}/'.format(t.port) - else: - url = 'http://{0}:{1}/'.format(t.host, t.port) - - if sys.platform.startswith('darwin'): - subprocess.call(('open', url), stdout=dn, stderr=dn) - elif os.name == 'posix': - subprocess.call(('xdg-open', url), stdout=dn, stderr=dn) - - while True: - try: - time.sleep(3600) - except KeyboardInterrupt: - t.shutdown() - t.join() - break - -# vi:ts=4:et diff --git a/cldoc/comment.py b/cldoc/comment.py index 229ec77..22f9c91 100644 --- a/cldoc/comment.py +++ b/cldoc/comment.py @@ -1,494 +1,483 @@ -# This file is part of cldoc. cldoc is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from .clang import cindex -from .defdict import Defdict - -from .struct import Struct -from . import utf8 - -import os, re, sys, bisect - -class Sorted(list): - def __init__(self, key=None): - if key is None: - key = lambda x: x - - self.keys = [] - self.key = key - - def insert_bisect(self, item, bi): - k = self.key(item) - idx = bi(self.keys, k) - - self.keys.insert(idx, k) - return super(Sorted, self).insert(idx, item) - - def insert(self, item): - return self.insert_bisect(item, bisect.bisect_left) - - insert_left = insert - - def insert_right(self, item): - return self.insert_bisect(item, bisect.bisect_right) - - def bisect(self, item, bi): - k = self.key(item) - - return bi(self.keys, k) - - def bisect_left(self, item): - return self.bisect(item, bisect.bisect_left) - - def bisect_right(self, item): - return self.bisect(item, bisect.bisect_right) - - def find(self, key): - i = bisect.bisect_left(self.keys, key) - - if i != len(self.keys) and self.keys[i] == key: - return self[i] - else: - return None - -class Comment(object): - class Example(str): - def __new__(self, s, strip=True): - if strip: - s = '\n'.join([self._strip_prefix(x) for x in s.split('\n')]) - - return str.__new__(self, s) - - @staticmethod - def _strip_prefix(s): - if s.startswith(' '): - return s[4:] - else: - return s - - class String(object): - def __init__(self, s): - self.components = [utf8.utf8(s)] - - def _utf8(self): - return utf8.utf8("").join([utf8.utf8(x) for x in self.components]) - - def __str__(self): - return str(self._utf8()) - - def __unicode__(self): - return unicode(self._utf8()) - - def __bytes__(self): - return bytes(self._utf8()) - - def __eq__(self, other): - if isinstance(other, str): - return str(self) == other - elif isinstance(other, unicode): - return unicode(self) == other - elif isinstance(other, bytes): - return bytes(self) == other - else: - return object.__cmp__(self, other) - - def __nonzero__(self): - l = len(self.components) - - return l > 0 and (l > 1 or len(self.components[0]) > 0) - - class MarkdownCode(utf8.utf8): - pass - - class UnresolvedReference(utf8.utf8): - reescape = re.compile('[*_]', re.I) - - def __new__(cls, s): - ns = Comment.UnresolvedReference.reescape.sub(lambda x: '\\' + x.group(0), s) - ret = utf8.utf8.__new__(cls, utf8.utf8('<{0}>').format(utf8.utf8(ns))) - - ret.orig = s - return ret - - redocref = re.compile('(?P[$]?)<(?:\\[(?P[^\\]]*)\\])?(?Poperator(?:>>|>|>=)|[^>\n]+)>') - redoccode = re.compile('^ \\[code\\]\n(?P(?:(?: .*|)\n)*)', re.M) - redocmcode = re.compile('(^ *(`{3,}|~{3,}).*?\\2)', re.M | re.S) - - def __init__(self, text, location): - self.__dict__['docstrings'] = [] - self.__dict__['text'] = text - - self.__dict__['location'] = location - self.__dict__['_resolved'] = False - - self.doc = text - self.brief = '' - - def __setattr__(self, name, val): - if not name in self.docstrings: - self.docstrings.append(name) - - if isinstance(val, dict): - for key in val: - if not isinstance(val[key], Comment.String): - val[key] = Comment.String(val[key]) - elif not isinstance(val, Comment.String): - val = Comment.String(val) - - self.__dict__[name] = val - - def __nonzero__(self): - return (bool(self.brief) and not (self.brief == u'*documentation missing...*')) or (bool(self.doc) and not (self.doc == u'*documentation missing...*')) - - def redoccode_split(self, doc): - # Split on C/C++ code - components = Comment.redoccode.split(doc) - ret = [] - - for i in range(0, len(components), 2): - r = Comment.redocmcode.split(components[i]) - - for j in range(0, len(r), 3): - ret.append(r[j]) - - if j < len(r) - 1: - ret.append(Comment.MarkdownCode(r[j + 1])) - - if i < len(components) - 1: - ret.append(Comment.Example(components[i + 1])) - - return ret - - def redoc_split(self, doc): - ret = [] - - # First split examples - components = self.redoccode_split(doc) - - for c in components: - if isinstance(c, Comment.Example) or isinstance(c, Comment.MarkdownCode): - ret.append((c, None, None)) - else: - lastpos = 0 - - for m in Comment.redocref.finditer(c): - span = m.span(0) - - prefix = c[lastpos:span[0]] - lastpos = span[1] - - ref = m.group('ref') - refname = m.group('refname') - - if not refname: - refname = None - - if len(m.group('isregex')) > 0: - ref = re.compile(ref) - - ret.append((prefix, ref, refname)) - - ret.append((c[lastpos:], None, None)) - - return ret - - def resolve_refs_for_doc(self, doc, resolver, root): - comps = self.redoc_split(utf8.utf8(doc)) - components = [] - - for pair in comps: - prefix, name, refname = pair - components.append(prefix) - - if name is None: - continue - - if isinstance(name, utf8.string): - names = name.split('::') - else: - names = [name] - - nds = [root] - - for j in range(len(names)): - newnds = [] - - for n in nds: - newnds += resolver(n, names[j], j == 0) - - if len(newnds) == 0: - break - - nds = newnds - - if len(newnds) > 0: - components.append((newnds, refname)) - else: - components.append(Comment.UnresolvedReference(name)) - - doc.components = components - - def resolve_refs(self, resolver, root): - if self.__dict__['_resolved']: - return - - self.__dict__['_resolved'] = True - - for name in self.docstrings: - doc = getattr(self, name) - - if not doc: - continue - - if isinstance(doc, dict): - for key in doc: - if not isinstance(doc[key], Comment.String): - doc[key] = Comment.String(doc[key]) - - self.resolve_refs_for_doc(doc[key], resolver, root) - else: - self.resolve_refs_for_doc(doc, resolver, root) - -class RangeMap(Sorted): - Item = Struct.define('Item', obj=None, start=0, end=0) - - def __init__(self): - super(RangeMap, self).__init__(key=lambda x: x.start) - - self.stack = [] - - def push(self, obj, start): - self.stack.append(RangeMap.Item(obj=obj, start=start, end=start)) - - def pop(self, end): - item = self.stack.pop() - item.end = end - - self.insert(item) - - def insert(self, item, start=None, end=None): - if not isinstance(item, RangeMap.Item): - item = RangeMap.Item(obj=item, start=start, end=end) - - self.insert_right(item) - - def find(self, i): - # Finds object for which i falls in the range of that object - idx = bisect.bisect_right(self.keys, i) - - # Go back up until falls within end - while idx > 0: - idx -= 1 - - o = self[idx] - - if i <= o.end: - return o.obj - - return None - -class CommentsDatabase(object): - cldoc_instrre = re.compile('^cldoc:([a-zA-Z_-]+)(\(([^\)]*)\))?') - - def __init__(self, filename, tu): - self.filename = filename - - self.categories = RangeMap() - self.comments = Sorted(key=lambda x: x.location.offset) - - self.extract(filename, tu) - - def parse_cldoc_instruction(self, token, s): - m = CommentsDatabase.cldoc_instrre.match(s) - - if not m: - return False - - func = m.group(1) - args = m.group(3) - - if args: - args = [x.strip() for x in args.split(",")] - else: - args = [] - - name = 'cldoc_instruction_{0}'.format(func.replace('-', '_')) - - if hasattr(self, name): - getattr(self, name)(token, args) - else: - sys.stderr.write('Invalid cldoc instruction: {0}\n'.format(func)) - sys.exit(1) - - return True - - @property - def category_names(self): - for item in self.categories: - yield item.obj - - def location_to_str(self, loc): - return '{0}:{1}:{2}'.format(loc.file.name, loc.line, loc.column) - - def cldoc_instruction_begin_category(self, token, args): - if len(args) != 1: - sys.stderr.write('No category name specified (at {0})\n'.format(self.location_to_str(token.location))) - - sys.exit(1) - - category = args[0] - self.categories.push(category, token.location.offset) - - def cldoc_instruction_end_category(self, token, args): - if len(self.categories.stack) == 0: - sys.stderr.write('Failed to end cldoc category: no category to end (at {0})\n'.format(self.location_to_str(token.location))) - - sys.exit(1) - - last = self.categories.stack[-1] - - if len(args) == 1 and last.obj != args[0]: - sys.stderr.write('Failed to end cldoc category: current category is `{0}\', not `{1}\' (at {2})\n'.format(last.obj, args[0], self.location_to_str(token.location))) - - sys.exit(1) - - self.categories.pop(token.extent.end.offset) - - def lookup_category(self, location): - if location.file.name != self.filename: - return None - - return self.categories.find(location.offset) - - def lookup(self, location): - if location.file.name != self.filename: - return None - - return self.comments.find(location.offset) - - def extract(self, filename, tu): - """ - extract extracts comments from a translation unit for a given file by - iterating over all the tokens in the TU, locating the COMMENT tokens and - finding out to which cursors the comments semantically belong. - """ - it = tu.get_tokens(extent=tu.get_extent(filename, (0, int(os.stat(filename).st_size)))) - - while True: - try: - self.extract_loop(it) - except StopIteration: - break - - def extract_one(self, token, s): - # Parse special cldoc:() comments for instructions - if self.parse_cldoc_instruction(token, s.strip()): - return - - comment = Comment(s, token.location) - self.comments.insert(comment) - - def extract_loop(self, iter): - token = next(iter) - - # Skip until comment found - while token.kind != cindex.TokenKind.COMMENT: - token = next(iter) - - comments = [] - prev = None - - # Concatenate individual comments together, but only if they are strictly - # adjacent - while token.kind == cindex.TokenKind.COMMENT: - cleaned = self.clean(token) - - # Process instructions directly, now - if (not cleaned is None) and (not CommentsDatabase.cldoc_instrre.match(cleaned) is None): - comments = [cleaned] - break - - # Check adjacency - if not prev is None and prev.extent.end.line + 1 < token.extent.start.line: - # Empty previous comment - comments = [] - - if not cleaned is None: - comments.append(cleaned) - - prev = token - token = next(iter) - - if len(comments) > 0: - self.extract_one(token, "\n".join(comments)) - - def clean(self, token): - prelen = token.extent.start.column - 1 - comment = token.spelling.strip() - - if comment.startswith('//'): - if len(comment) > 2 and comment[2] == '-': - return None - - return comment[2:].strip() - elif comment.startswith('/*') and comment.endswith('*/'): - if comment[2] == '-': - return None - - lines = comment[2:-2].splitlines() - - if len(lines) == 1 and len(lines[0]) > 0 and lines[0][0] == ' ': - return lines[0][1:].rstrip() - - retl = [] - - for line in lines: - if prelen == 0 or line[0:prelen].isspace(): - line = line[prelen:].rstrip() - - if line.startswith(' *') or line.startswith(' '): - line = line[2:] - - if len(line) > 0 and line[0] == ' ': - line = line[1:] - - retl.append(line) - - return "\n".join(retl) - else: - return comment - -from pyparsing import * - -class Parser: - ParserElement.setDefaultWhitespaceChars(' \t\r') - - identifier = Word(alphas + '_', alphanums + '_') - - brief = restOfLine.setResultsName('brief') + lineEnd - - paramdesc = restOfLine + ZeroOrMore(lineEnd + ~('@' | lineEnd) + Regex('[^\n]+')) + lineEnd.suppress() - param = '@' + identifier.setResultsName('name') + White() + Combine(paramdesc).setResultsName('description') - - preparams = ZeroOrMore(param.setResultsName('preparam', listAllMatches=True)) - postparams = ZeroOrMore(param.setResultsName('postparam', listAllMatches=True)) - - bodyline = NotAny('@') + (lineEnd | (Regex('[^\n]+') + lineEnd)) - body = ZeroOrMore(lineEnd) + Combine(ZeroOrMore(bodyline)).setResultsName('body') - - doc = brief + preparams + body + postparams - - @staticmethod - def parse(s): - return Parser.doc.parseString(s) - -# vi:ts=4:et +# This file is part of cldoc. cldoc is free software: you can +# redistribute it and/or modify it under the terms of the GNU General Public +# License as published by the Free Software Foundation, version 2. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +# details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, write to the Free Software Foundation, Inc., 51 +# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +from .clang import cindex +from cldoc import parser + +from .struct import Struct +from . import utf8 +from .parser import * +from pyparsing import * + +import os, re, sys, bisect + +class Sorted(list): + def __init__(self, key=None): + if key is None: + key = lambda x: x + + self.keys = [] + self.key = key + + def insert_bisect(self, item, bi): + k = self.key(item) + idx = bi(self.keys, k) + + self.keys.insert(idx, k) + return super(Sorted, self).insert(idx, item) + + def insert(self, item): + return self.insert_bisect(item, bisect.bisect_left) + + insert_left = insert + + def insert_right(self, item): + return self.insert_bisect(item, bisect.bisect_right) + + def bisect(self, item, bi): + k = self.key(item) + + return bi(self.keys, k) + + def bisect_left(self, item): + return self.bisect(item, bisect.bisect_left) + + def bisect_right(self, item): + return self.bisect(item, bisect.bisect_right) + + def find(self, key): + i = bisect.bisect_right(self.keys, key) + if i<=0 or i>len(self.keys): + return None + self.keys.pop(i-1) + result=self.pop(i-1) + return result + +class Comment(object): + parser=Parser() + class Example(str): + def __new__(self, s, strip=True): + if strip: + s = '\n'.join([self._strip_prefix(x) for x in s.split('\n')]) + + return str.__new__(self, s) + + @staticmethod + def _strip_prefix(s): + if s.startswith(' '): + return s[4:] + else: + return s + + class String(object): + def __init__(self, s, pth, fn, ln): + self.components = [utf8.utf8(s)] + self.path=pth + self.filename=fn + self.start_line=ln + + def _utf8(self): + return utf8.utf8("").join([utf8.utf8(x) for x in self.components]) + + def __str__(self): + return str(self._utf8()) + + def __unicode__(self): + return unicode(self._utf8()) + + def __bytes__(self): + return bytes(self._utf8()) + + def __eq__(self, other): + if isinstance(other, str): + return str(self) == other + elif isinstance(other, unicode): + return unicode(self) == other + elif isinstance(other, bytes): + return bytes(self) == other + else: + return object.__cmp__(self, other) + + def __nonzero__(self): + l = len(self.components) + + return l > 0 and (l > 1 or len(self.components[0]) > 0) + + class MarkdownCode(utf8.utf8): + pass + + class UnresolvedReference(utf8.utf8): + reescape = re.compile('[*_]', re.I) + + def __new__(cls, s): + ns = Comment.UnresolvedReference.reescape.sub(lambda x: '\\' + x.group(0), s) + ret = utf8.utf8.__new__(cls, utf8.utf8('<{0}>').format(utf8.utf8(ns))) + + ret.orig = s + return ret + + redocref = re.compile('(?P[$]?)<(?:\\[(?P[^\\]]*)\\])?(?Poperator(?:>>|>|>=)|[^>\n]+)>') + redoccode = re.compile('^ \\[code\\]\n(?P(?:(?: .*|)\n)*)', re.M) + redocmcode = re.compile('(^ *(`{3,}|~{3,}).*?\\2)', re.M | re.S) + + def __init__(self, text, location, opts): + ln=0 + if isinstance(location,cindex.SourceLocation): + location=(location.file.name,location.line,location.column,location.offset) + spl=os.path.split(location[0]) + ln=location[1] + cl=location[2] + + object.__setattr__(self, 'path', spl[0]) + object.__setattr__(self, 'start_line', ln) + object.__setattr__(self, 'filename', spl[1]) + self.__dict__['docstrings'] = [] + self.__dict__['text'] = text + + self.__dict__['location'] = location + self.__dict__['_resolved'] = False + self.global_properties={} + + self.doc = text + self.brief = '' + self.images=[] + self.imagepaths=[] + self.options=opts + self.parsedComment=ParsedComment() + + def __setattr__(self, name, val): + # if not name in self.docstrings: + # self.docstrings.append(name) + if isinstance(val, dict): + for key in val: + if not isinstance(val[key], Comment.String): + val[key] = Comment.String(val[key],self.path,self.filename,self.start_line) + # Let's NOT change the class of members arbitrarily... + elif isinstance(val, str) or isinstance(val, ParseResults): + val = Comment.String(val,self.path,self.filename,self.start_line) + else: + object.__setattr__(self, name, val) + return # ordinary class members + if not name in self.docstrings: + self.docstrings.append(name) + + self.__dict__[name] = val + + def __nonzero__(self): + return (bool(self.brief) and not (self.brief == u'*documentation missing...*')) or (bool(self.doc) and not (self.doc == u'*documentation missing...*')) + + def redoccode_split(self, doc): + # Split on C/C++ code + components = Comment.redoccode.split(doc) + ret = [] + + for i in range(0, len(components), 2): + r = Comment.redocmcode.split(components[i]) + + for j in range(0, len(r), 3): + ret.append(r[j]) + + if j < len(r) - 1: + ret.append(Comment.MarkdownCode(r[j + 1])) + + if i < len(components) - 1: + ret.append(Comment.Example(components[i + 1])) + + return ret + + def redoc_split(self, doc): + ret = [] + + # First split examples + components = self.redoccode_split(doc) + + for c in components: + if isinstance(c, Comment.Example) or isinstance(c, Comment.MarkdownCode): + ret.append((c, None, None)) + else: + lastpos = 0 + + for m in Comment.redocref.finditer(c): + span = m.span(0) + + prefix = c[lastpos:span[0]] + lastpos = span[1] + + ref = m.group('ref') + refname = m.group('refname') + + if not refname: + refname = None + + if len(m.group('isregex')) > 0: + ref = re.compile(ref) + + ret.append((prefix, ref, refname)) + + ret.append((c[lastpos:], None, None)) + + return ret + def merge_two_dicts(x, y): + z = x.copy() # start with x's keys and values + z.update(y) # modifies z with y's keys and values & returns None + return z + def resolve_refs_for_doc(self, doc, resolver, root): + Comment.parser.reset() + comps=[] + for comp in doc.components: + if isinstance(comp, str): + comps+=Comment.parser.parseFull(comp, resolver, root, doc.path,doc.filename, doc.start_line) + self.global_properties.update(Comment.parser.properties) + else: + comps.append(comp) + + doc.components = comps + + def resolve_refs(self, resolver, root): + if self.__dict__['_resolved']: + return + + self.__dict__['_resolved'] = True + + # Each docstring: brief, doc, etc, will become a Comment.String with a list of components, which may be strings or node links. + for name in self.docstrings: + doc = getattr(self, name) + + if not doc: + continue + + if isinstance(doc, dict): + for key in doc: + if not isinstance(doc[key], Comment.String): + doc[key] = Comment.String(doc[key],self.path,self.filename,self.start_line) + + self.resolve_refs_for_doc(doc[key], resolver, root) + else: + self.resolve_refs_for_doc(doc, resolver, root) + if self.parsedComment is ParsedComment: + self.parsedComment.resolve_cross_refs(resolver,root) + +class RangeMap(Sorted): + Item = Struct.define('Item', obj=None, start=0, end=0) + + def __init__(self): + super(RangeMap, self).__init__(key=lambda x: x.start) + + self.stack = [] + + def push(self, obj, start): + self.stack.append(RangeMap.Item(obj=obj, start=start, end=start)) + + def pop(self, end): + item = self.stack.pop() + item.end = end + + self.insert(item) + + def insert(self, item, start=None, end=None): + if not isinstance(item, RangeMap.Item): + item = RangeMap.Item(obj=item, start=start, end=end) + + self.insert_right(item) + + def find(self, i): + # Finds object for which i falls in the range of that object + idx = bisect.bisect_right(self.keys, i) + + # Go back up until falls within end + while idx > 0: + idx -= 1 + + o = self[idx] + + if i <= o.end: + return o.obj + + return None + +class CommentsDatabase(object): + cldoc_instrre = re.compile('^cldoc:([a-zA-Z_-]+)(\(([^\)]*)\))?') + + def __init__(self, filename, tu, opts): + self.filename = filename + + self.categories = RangeMap() + self.comments = Sorted(key=lambda x: x.location[3]) + self.options=opts + self.extract(filename, tu) + + def parse_cldoc_instruction(self, token, s): + m = CommentsDatabase.cldoc_instrre.match(s) + + if not m: + return False + + func = m.group(1) + args = m.group(3) + + if args: + args = [x.strip() for x in args.split(",")] + else: + args = [] + + name = 'cldoc_instruction_{0}'.format(func.replace('-', '_')) + + if hasattr(self, name): + getattr(self, name)(token, args) + else: + sys.stderr.write('Invalid cldoc instruction: {0}\n'.format(func)) + sys.exit(1) + + return True + + @property + def category_names(self): + for item in self.categories: + yield item.obj + + def location_to_str(self, loc): + return '{0}:{1}:{2}'.format(loc.file.name, loc.line, loc.column) + + def cldoc_instruction_begin_category(self, token, args): + if len(args) != 1: + sys.stderr.write('No category name specified (at {0})\n'.format(self.location_to_str(token.location))) + + sys.exit(1) + + category = args[0] + self.categories.push(category, token.location.offset) + + def cldoc_instruction_end_category(self, token, args): + if len(self.categories.stack) == 0: + sys.stderr.write('Failed to end cldoc category: no category to end (at {0})\n'.format(self.location_to_str(token.location))) + + sys.exit(1) + + last = self.categories.stack[-1] + + if len(args) == 1 and last.obj != args[0]: + sys.stderr.write('Failed to end cldoc category: current category is `{0}\', not `{1}\' (at {2})\n'.format(last.obj, args[0], self.location_to_str(token.location))) + + sys.exit(1) + + self.categories.pop(token.extent.end.offset) + + def lookup_category(self, location): + if location.file.name != self.filename: + return None + + return self.categories.find(location.offset) + + def lookup(self, location): + if location[0]!= self.filename: + return None + + return self.comments.find(location[3]) #offset + + def extract(self, filename, tu): + """ + extract extracts comments from a translation unit for a given file by + iterating over all the tokens in the TU, locating the COMMENT tokens and + finding out to which cursors the comments semantically belong. + """ + it = tu.get_tokens(extent=tu.get_extent(filename, (0, int(os.stat(filename).st_size)))) + + while True: + try: + self.extract_loop(it) + except StopIteration: + break + + def extract_one(self, token, s): + # Parse special cldoc:() comments for instructions + if self.parse_cldoc_instruction(token, s.strip()): + return + + comment = Comment(s, token.location,self.options) + self.comments.insert(comment) + + def extract_loop(self, iter): + token = next(iter) + + # Skip until comment found + while token.kind != cindex.TokenKind.COMMENT: + token = next(iter) + + comments = [] + prev = None + + # Concatenate individual comments together, but only if they are strictly + # adjacent + while token.kind == cindex.TokenKind.COMMENT: + cleaned = self.clean(token) + + # Process instructions directly, now + if (not cleaned is None) and (not CommentsDatabase.cldoc_instrre.match(cleaned) is None): + comments = [cleaned] + break + + # Check adjacency + if not prev is None and prev.extent.end.line + 1 < token.extent.start.line: + # Empty previous comment + comments = [] + + if not cleaned is None: + comments.append(cleaned) + + prev = token + token = next(iter) + + if len(comments) > 0: + self.extract_one(token, "\n".join(comments)) + + def clean(self, token): + prelen = token.extent.start.column - 1 + comment = token.spelling.strip() + + if comment.startswith('///') or comment.startswith('//!'): + return comment[3:].strip() + elif comment.startswith('//'): + # For our purposes, ordinary comments are ignored. + return None + #if len(comment) > 2 and comment[2] == '-': + # return None + + return comment[2:].strip() + elif comment.startswith('/*') and comment.endswith('*/'): + # For our purposes, ! is required here. + if comment[2] != '!': + return None + + lines = comment[3:-2].splitlines() + + if len(lines) == 1 and len(lines[0]) > 0 and lines[0][0] == ' ': + return lines[0][1:].rstrip() + + retl = [] + + for line in lines: + if prelen == 0 or line[0:prelen].isspace(): + line = line[prelen:].rstrip() + + if line.startswith(' *') or line.startswith(' '): + line = line[2:] + + if len(line) > 0 and line[0] == ' ': + line = line[1:] + + retl.append(line) + + return "\n".join(retl) + else: + return comment + +# vi:ts=4:et diff --git a/cldoc/data/javascript/cldoc.js b/cldoc/data/javascript/cldoc.js index 186cfcb..a3b8916 100644 --- a/cldoc/data/javascript/cldoc.js +++ b/cldoc/data/javascript/cldoc.js @@ -16,31 +16,31 @@ window.cldoc = $.extend($.extend({ host: href.substring(0, href.lastIndexOf('/')) }, (ref1 = window.cldoc) != null ? ref1 : {}), { tag: function(node) { - return $.map(node, function(e) { - return e.tagName.toLowerCase(); - }); +\treturn $.map(node, function(e) { +\t return e.tagName.toLowerCase(); +\t}); }, startswith: function(s, prefix) { - return s.indexOf(prefix) === 0; +\treturn s.indexOf(prefix) === 0; }, html_escape: function(s) { - escapeElement.data = s; - return escapeDiv.innerHTML; +\tescapeElement.data = s; +\treturn escapeDiv.innerHTML; }, new_timer: function() { - var ret; - ret = { - start: new Date() - }; - ret.tick = function(s) { - var end; - end = new Date(); - return ret.start = end; - }; - return ret; +\tvar ret; +\tret = { +\t start: new Date() +\t}; +\tret.tick = function(s) { +\t var end; +\t end = new Date(); +\t return ret.start = end; +\t}; +\treturn ret; }, xml_attr: function(e, a) { - return e.getAttribute(a); +\treturn e.getAttribute(a); } }); @@ -54,143 +54,143 @@ cldoc.SearchWorker = function() { var bsearch, db, load_db, log, search_term; db = null; log = function(msg) { - return self.postMessage({ - type: 'log', - message: msg - }); +\treturn self.postMessage({ +\t type: 'log', +\t message: msg +\t}); }; load_db = function(host) { - var xhr; - xhr = new XMLHttpRequest(); - xhr.open('GET', host + '/search.json?' + new Date().getTime(), false); - xhr.send(); - return JSON.parse(xhr.responseText); +\tvar xhr; +\txhr = new XMLHttpRequest(); +\txhr.open('GET', host + '/search.json?' + new Date().getTime(), false); +\txhr.send(); +\treturn JSON.parse(xhr.responseText); }; bsearch = (function(_this) { - return function(term, l, r, sel) { - var mid, rec, ref2, suf, suffix_record; - suffix_record = function(i) { - return db.suffixes[i][0]; - }; - while (l < r) { - mid = Math.floor((l + r) / 2); - rec = suffix_record(mid); - suf = db.records[rec[0]][0].substring(rec[1]); - ref2 = sel(suf) ? [mid + 1, r] : [l, mid], l = ref2[0], r = ref2[1]; - } - return [l, r]; - }; +\treturn function(term, l, r, sel) { +\t var mid, rec, ref2, suf, suffix_record; +\t suffix_record = function(i) { +\t\treturn db.suffixes[i][0]; +\t }; +\t while (l < r) { +\t\tmid = Math.floor((l + r) / 2); +\t\trec = suffix_record(mid); +\t\tsuf = db.records[rec[0]][0].substring(rec[1]); +\t\tref2 = sel(suf) ? [mid + 1, r] : [l, mid], l = ref2[0], r = ref2[1]; +\t } +\t return [l, r]; +\t}; })(this); search_term = (function(_this) { - return function(term) { - var _, end, l, r, ref2, ref3, start, t; - if (term.length < 3) { - return [0, 0]; - } - l = 0; - r = db.suffixes.length; - t = term.toLowerCase(); - ref2 = bsearch(t, 0, db.suffixes.length, function(suf) { - return t > suf; - }), start = ref2[0], _ = ref2[1]; - ref3 = bsearch(t, start, db.suffixes.length, function(suf) { - return suf.indexOf(t) === 0; - }), _ = ref3[0], end = ref3[1]; - return [start, end]; - }; +\treturn function(term) { +\t var _, end, l, r, ref2, ref3, start, t; +\t if (term.length < 3) { +\t\treturn [0, 0]; +\t } +\t l = 0; +\t r = db.suffixes.length; +\t t = term.toLowerCase(); +\t ref2 = bsearch(t, 0, db.suffixes.length, function(suf) { +\t\treturn t > suf; +\t }), start = ref2[0], _ = ref2[1]; +\t ref3 = bsearch(t, start, db.suffixes.length, function(suf) { +\t\treturn suf.indexOf(t) === 0; +\t }), _ = ref3[0], end = ref3[1]; +\t return [start, end]; +\t}; })(this); return self.onmessage = (function(_this) { - return function(ev) { - var end, i, items, j, len, len1, m, o, p, rec, recid, records, ref2, ref3, ref4, ret, rr, start, word, words; - m = ev.data; - if (db === null) { - db = load_db(m.host); - } - words = m.q.split(/\s+/); - records = {}; - ret = { - type: 'result', - id: m.id, - q: m.q, - words: words, - records: [] - }; - for (j = 0, len = words.length; j < len; j++) { - word = words[j]; - ref2 = search_term(word), start = ref2[0], end = ref2[1]; - for (i = o = ref3 = start, ref4 = end - 1; o <= ref4; i = o += 1) { - items = db.suffixes[i]; - for (p = 0, len1 = items.length; p < len1; p++) { - rec = items[p]; - recid = rec[0]; - if (!(recid in records)) { - rr = { - name: db.records[recid][0], - id: db.records[recid][1], - score: 0, - results: [], - suffixhash: {} - }; - ret.records.push(rr); - records[recid] = rr; - } else { - rr = records[recid]; - } - if (!(rec[1] in rr.suffixhash)) { - rr.score += 1; - rr.results.push([rec[1], rec[1] + word.length]); - rr.suffixhash[rec[1]] = true; - } - } - } - } - ret.records.sort(function(a, b) { - var ref5, ref6; - return (ref5 = a.score > b.score) != null ? ref5 : (ref6 = a.score < b.score) != null ? ref6 : -{ - 1: 0 - }; - }); - return self.postMessage(ret); - }; +\treturn function(ev) { +\t var end, i, items, j, len, len1, m, o, p, rec, recid, records, ref2, ref3, ref4, ret, rr, start, word, words; +\t m = ev.data; +\t if (db === null) { +\t\tdb = load_db(m.host); +\t } +\t words = m.q.split(/\s+/); +\t records = {}; +\t ret = { +\t\ttype: 'result', +\t\tid: m.id, +\t\tq: m.q, +\t\twords: words, +\t\trecords: [] +\t }; +\t for (j = 0, len = words.length; j < len; j++) { +\t\tword = words[j]; +\t\tref2 = search_term(word), start = ref2[0], end = ref2[1]; +\t\tfor (i = o = ref3 = start, ref4 = end - 1; o <= ref4; i = o += 1) { +\t\t items = db.suffixes[i]; +\t\t for (p = 0, len1 = items.length; p < len1; p++) { +\t\t\trec = items[p]; +\t\t\trecid = rec[0]; +\t\t\tif (!(recid in records)) { +\t\t\t rr = { +\t\t\t\tname: db.records[recid][0], +\t\t\t\tid: db.records[recid][1], +\t\t\t\tscore: 0, +\t\t\t\tresults: [], +\t\t\t\tsuffixhash: {} +\t\t\t }; +\t\t\t ret.records.push(rr); +\t\t\t records[recid] = rr; +\t\t\t} else { +\t\t\t rr = records[recid]; +\t\t\t} +\t\t\tif (!(rec[1] in rr.suffixhash)) { +\t\t\t rr.score += 1; +\t\t\t rr.results.push([rec[1], rec[1] + word.length]); +\t\t\t rr.suffixhash[rec[1]] = true; +\t\t\t} +\t\t } +\t\t} +\t } +\t ret.records.sort(function(a, b) { +\t\tvar ref5, ref6; +\t\treturn (ref5 = a.score > b.score) != null ? ref5 : (ref6 = a.score < b.score) != null ? ref6 : -{ +\t\t 1: 0 +\t\t}; +\t }); +\t return self.postMessage(ret); +\t}; })(this); }; cldoc.SearchDb = (function() { function SearchDb() { - var blob, ref2, wurl; - this.searchid = 0; - this.searchcb = null; - wurl = (ref2 = window.webkitURL) != null ? ref2 : window.URL; - blob = new Blob(['worker = ' + cldoc.SearchWorker.toString() + '; worker();'], { - type: 'text/javascript' - }); - this.worker = new Worker(wurl.createObjectURL(blob)); - this.worker.onmessage = (function(_this) { - return function(msg) { - var m; - m = msg.data; - if (m.type === 'log') { - return console.log(m.message); - } else if (m.type === 'result') { - if (m.id !== _this.searchid) { - return; - } - _this.searchid = 0; - return _this.searchcb(m); - } - }; - })(this); +\tvar blob, ref2, wurl; +\tthis.searchid = 0; +\tthis.searchcb = null; +\twurl = (ref2 = window.webkitURL) != null ? ref2 : window.URL; +\tblob = new Blob(['worker = ' + cldoc.SearchWorker.toString() + '; worker();'], { +\t type: 'text/javascript' +\t}); +\tthis.worker = new Worker(wurl.createObjectURL(blob)); +\tthis.worker.onmessage = (function(_this) { +\t return function(msg) { +\t\tvar m; +\t\tm = msg.data; +\t\tif (m.type === 'log') { +\t\t return console.log(m.message); +\t\t} else if (m.type === 'result') { +\t\t if (m.id !== _this.searchid) { +\t\t\treturn; +\t\t } +\t\t _this.searchid = 0; +\t\t return _this.searchcb(m); +\t\t} +\t }; +\t})(this); } SearchDb.prototype.search = function(q, cb) { - this.searchid += 1; - this.searchcb = cb; - return this.worker.postMessage({ - type: 'search', - q: q, - id: this.searchid, - host: cldoc.host - }); +\tthis.searchid += 1; +\tthis.searchcb = cb; +\treturn this.worker.postMessage({ +\t type: 'search', +\t q: q, +\t id: this.searchid, +\t host: cldoc.host +\t}); }; return SearchDb; @@ -207,588 +207,588 @@ cldoc.Page = (function() { Page.first = true; Page.search = { - db: null +\tdb: null }; Page.request_page = function(page, cb) { - var url; - if (page in this.pages) { - cb(this.pages[page]); - return; - } - url = cldoc.host + '/xml/' + page.replace(/::/g, '.') + '.xml'; - return $.ajax({ - url: url, - cache: false, - success: (function(_this) { - return function(data) { - _this.pages[page] = { - xml: $(data), - html: null - }; - return cb(_this.pages[page]); - }; - })(this) - }); +\tvar url; +\tif (page in this.pages) { +\t cb(this.pages[page]); +\t return; +\t} +\turl = cldoc.host + '/xml/' + page.replace(/::/g, '.') + '.xml'; +\treturn $.ajax({ +\t url: url, +\t cache: false, +\t success: (function(_this) { +\t\treturn function(data) { +\t\t _this.pages[page] = { +\t\t\txml: $(data), +\t\t\thtml: null +\t\t }; +\t\t return cb(_this.pages[page]); +\t\t}; +\t })(this) +\t}); }; Page.load = function(page, scrollto, updatenav) { - cldoc.Sidebar.exit_search(); - if (page === null || page === 'undefined') { - page = this.current_page; - } - if (!page) { - page = 'index'; - } - if (updatenav) { - this.push_nav(page, scrollto); - } - if (this.current_page !== page) { - return this.request_page(page, (function(_this) { - return function() { - return _this.load_page(page, scrollto); - }; - })(this)); - } else { - return this.scroll(page, scrollto); - } +\tcldoc.Sidebar.exit_search(); +\tif (page === null || page === 'undefined') { +\t page = this.current_page; +\t} +\tif (!page) { +\t page = 'index'; +\t} +\tif (updatenav) { +\t this.push_nav(page, scrollto); +\t} +\tif (this.current_page !== page) { +\t return this.request_page(page, (function(_this) { +\t\treturn function() { +\t\t return _this.load_page(page, scrollto); +\t\t}; +\t })(this)); +\t} else { +\t return this.scroll(page, scrollto); +\t} }; Page.make_link = function(ref, name, attrs) { - var e, k, r, ret, v; - if (attrs == null) { - attrs = {}; - } - e = cldoc.html_escape; - r = this.make_internal_ref(ref); - ret = '' + e(name) + ''; +\tvar e, k, r, ret, v; +\tif (attrs == null) { +\t attrs = {}; +\t} +\te = cldoc.html_escape; +\tr = this.make_internal_ref(ref); +\tret = '' + e(name) + ''; }; Page.load_page = function(page, scrollto) { - var brief, content, cpage, data, html, root, sidebar, start, title; - this.first = this.current_page === null; - start = new Date(); - this.current_page = page; - cpage = this.pages[page]; - data = cpage.xml; - html = cpage.html; - $('#cldoc #cldoc_content').children().detach(); - root = data.children(':first'); - if (html) { - $('#cldoc #cldoc_content').append(html.content); - cldoc.Sidebar.load_html(html.sidebar); - } else { - sidebar = cldoc.Sidebar.load(root); - content = this.load_contents(root); - cpage.html = { - sidebar: sidebar, - content: content - }; - } - title = root.attr('name'); - if (!title) { - brief = root.children('brief'); - if (brief.length > 0) { - title = brief.text(); - if (title[title.length - 1] === '.') { - title = title.substring(0, title.length - 1); - } - } - } - if (!title) { - title = 'Documentation'; - } - document.title = title; - this.scroll(page, scrollto, true); - return $('#cldoc').triggerHandler('page-loaded', [root]); +\tvar brief, content, cpage, data, html, root, sidebar, start, title; +\tthis.first = this.current_page === null; +\tstart = new Date(); +\tthis.current_page = page; +\tcpage = this.pages[page]; +\tdata = cpage.xml; +\thtml = cpage.html; +\t$('#cldoc #cldoc_content').children().detach(); +\troot = data.children(':first'); +\tif (html) { +\t $('#cldoc #cldoc_content').append(html.content); +\t cldoc.Sidebar.load_html(html.sidebar); +\t} else { +\t sidebar = cldoc.Sidebar.load(root); +\t content = this.load_contents(root); +\t cpage.html = { +\t\tsidebar: sidebar, +\t\tcontent: content +\t }; +\t} +\ttitle = root.attr('name'); +\tif (!title) { +\t brief = root.children('brief'); +\t if (brief.length > 0) { +\t\ttitle = brief.text(); +\t\tif (title[title.length - 1] === '.') { +\t\t title = title.substring(0, title.length - 1); +\t\t} +\t } +\t} +\tif (!title) { +\t title = 'Documentation'; +\t} +\tdocument.title = title; +\tthis.scroll(page, scrollto, true); +\treturn $('#cldoc').triggerHandler('page-loaded', [root]); }; Page.make_external_ref = function(page, id) { - if (page[0] === '#') { - page = page.substring(1); - } - if (!id) { - return page.replace('/', '#'); - } else { - return page + '#' + id; - } +\tif (page[0] === '#') { +\t page = page.substring(1); +\t} +\tif (!id) { +\t return page.replace('/', '#'); +\t} else { +\t return page + '#' + id; +\t} }; Page.make_internal_ref = function(page, id) { - if (!page) { - return '#index'; - } - if (!id) { - return '#' + page.replace('#', '/'); - } else { - return '#' + page + '/' + id; - } +\tif (!page) { +\t return '#index'; +\t} +\tif (!id) { +\t return '#' + page.replace('#', '/'); +\t} else { +\t return '#' + page + '/' + id; +\t} }; Page.split_ref = function(ref) { - var id, page, ref2; - ref2 = ref.split('#', 2), page = ref2[0], id = ref2[1]; - if (!page) { - page = 'index'; - } - return [page, id]; +\tvar id, page, ref2; +\tref2 = ref.split('#', 2), page = ref2[0], id = ref2[1]; +\tif (!page) { +\t page = 'index'; +\t} +\treturn [page, id]; }; Page.load_ref = function(ref) { - var r; - r = this.split_ref(ref); - return this.load(r[0], r[1], true); +\tvar r; +\tr = this.split_ref(ref); +\treturn this.load(r[0], r[1], true); }; Page.make_header = function(item) { - var e, id, name, obj, ret, title, type; - id = item.attr('id'); - e = cldoc.html_escape; - if (id) { - ret = ''; - type = this.node_type(item); - title = item.attr('title'); - if (type) { - ret += '' + e(type.title[0]) + ''; - obj = new type(item); - name = obj.full_name_for_display(); - } else { - name = item.attr('name'); - } - if (title) { - ret += '' + e(title) + ''; - } else { - if (name) { - ret += '' + e(name) + ''; - } else { - ret += '' + e(id) + ''; - } - } - return ret; - } else { - return ''; - } +\tvar e, id, name, obj, ret, title, type; +\tid = item.attr('id'); +\te = cldoc.html_escape; +\tif (id) { +\t ret = ''; +\t type = this.node_type(item); +\t title = item.attr('title'); +\t if (type) { +\t\tret += '' + e(type.title[0]) + ''; +\t\tobj = new type(item); +\t\tname = obj.full_name_for_display(); +\t } else { +\t\tname = item.attr('name'); +\t } +\t if (title) { +\t\tret += '' + e(title) + ''; +\t } else { +\t\tif (name) { +\t\t ret += '' + e(name) + ''; +\t\t} else { +\t\t ret += '' + e(id) + ''; +\t\t} +\t } +\t return ret; +\t} else { +\t return ''; +\t} }; Page.load_description = function(page, content) { - var desc, doc, h1, id; - doc = cldoc.Doc.either(page); - id = page.attr('id'); - if (id) { - h1 = $('

').appendTo(content); - h1.attr('id', id); - h1.append(this.make_header(page)); - } - if (doc) { - desc = $('
'); - desc.append(doc); - return content.append(desc); - } +\tvar desc, doc, h1, id; +\tdoc = cldoc.Doc.either(page); +\tid = page.attr('id'); +\tif (id) { +\t h1 = $('

').appendTo(content); +\t h1.attr('id', id); +\t h1.append(this.make_header(page)); +\t} +\tif (doc) { +\t desc = $('
'); +\t desc.append(doc); +\t return content.append(desc); +\t} }; Page.node_type = function(item) { - var typename; - typename = cldoc.tag(item)[0]; - if (!(typename in cldoc.Node.types)) { - return null; - } - return cldoc.Node.types[typename]; +\tvar typename; +\ttypename = cldoc.tag(item)[0]; +\tif (!(typename in cldoc.Node.types)) { +\t return null; +\t} +\treturn cldoc.Node.types[typename]; }; Page.load_items = function(page) { - var all, container, content, e, group, item, itemcontents, items, j, len, len1, o, ref2, ret, tp, type; - all = page.children(); - content = ''; - e = cldoc.html_escape; - ref2 = cldoc.Node.groups; - for (j = 0, len = ref2.length; j < len; j++) { - group = ref2[j]; - items = all.filter(group); - if (items.length === 0) { - continue; - } - type = this.node_type(items); - if (!type || type === cldoc.Node.types.report) { - continue; - } - content += '

' + e(type.title[1]) + '

'; - container = type.render_container(); - itemcontents = ''; - for (o = 0, len1 = items.length; o < len1; o++) { - item = items[o]; - item = $(item); - if (cldoc.tag(item)[0] !== cldoc.tag(items)[0]) { - tp = this.node_type(item); - } else { - tp = type; - } - if (tp) { - ret = new tp($(item)).render(); - if (ret) { - itemcontents += ret; - } - } - } - if (container) { - content += container[0] + itemcontents + container[1]; - } else { - content += itemcontents; - } - } - return content; +\tvar all, container, content, e, group, item, itemcontents, items, j, len, len1, o, ref2, ret, tp, type; +\tall = page.children(); +\tcontent = ''; +\te = cldoc.html_escape; +\tref2 = cldoc.Node.groups; +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t group = ref2[j]; +\t items = all.filter(group); +\t if (items.length === 0) { +\t\tcontinue; +\t } +\t type = this.node_type(items); +\t if (!type || type === cldoc.Node.types.report) { +\t\tcontinue; +\t } +\t content += '

' + e(type.title[1]) + '

'; +\t container = type.render_container(); +\t itemcontents = ''; +\t for (o = 0, len1 = items.length; o < len1; o++) { +\t\titem = items[o]; +\t\titem = $(item); +\t\tif (cldoc.tag(item)[0] !== cldoc.tag(items)[0]) { +\t\t tp = this.node_type(item); +\t\t} else { +\t\t tp = type; +\t\t} +\t\tif (tp) { +\t\t ret = new tp($(item)).render(); +\t\t if (ret) { +\t\t\titemcontents += ret; +\t\t } +\t\t} +\t } +\t if (container) { +\t\tcontent += container[0] + itemcontents + container[1]; +\t } else { +\t\tcontent += itemcontents; +\t } +\t} +\treturn content; }; Page.bind_links = function(container) { - return container.find('a').on('click', (function(_this) { - return function(e) { - var ref; - ref = $(e.delegateTarget).attr('href'); - if (ref[0] === '#') { - _this.load_ref(_this.make_external_ref(ref)); - return false; - } else { - return true; - } - }; - })(this)); +\treturn container.find('a').on('click', (function(_this) { +\t return function(e) { +\t\tvar ref; +\t\tref = $(e.delegateTarget).attr('href'); +\t\tif (ref[0] === '#') { +\t\t _this.load_ref(_this.make_external_ref(ref)); +\t\t return false; +\t\t} else { +\t\t return true; +\t\t} +\t }; +\t})(this)); }; Page.load_pagenav = function(page, content) { - var h2cnt, h2li, h2ol, h3cnt, pagenav, ul; - if (this.node_type(page) !== cldoc.Category) { - return; - } - pagenav = $('#cldoc_sidebar_pagenav'); - ul = $('
    '); - h2cnt = 0; - h2li = null; - h2ol = null; - h3cnt = 0; - content.find('h2,h3').each((function(_this) { - return function(i, e) { - var a, h, id, ish2, li, t; - h = $(e); - if (h.attr('data-cldoc-dynamic')) { - return; - } - id = h.text(); - ish2 = e.tagName === 'H2'; - if (ish2) { - h2cnt += 1; - t = h2cnt + '. ' + id; - } else { - h3cnt += 1; - t = h2cnt + '.' + h3cnt + '. ' + id; - } - h.text(t); - h.attr('id', id); - a = $('', { - href: _this.make_internal_ref(_this.current_page, id) - }).text(t); - li = $('
  1. ').append(a); - if (!ish2 && h2li !== null) { - if (h2ol === null) { - h2ol = $('
      ').appendTo(h2li); - } - return h2ol.append(li); - } else { - if (ish2 && h2li === null) { - h2li = li; - h2ol = null; - } - return li.appendTo(ul); - } - }; - })(this)); - this.bind_links(ul); - return pagenav.append(ul); +\tvar h2cnt, h2li, h2ol, h3cnt, pagenav, ul; +\tif (this.node_type(page) !== cldoc.Category) { +\t return; +\t} +\tpagenav = $('#cldoc_sidebar_pagenav'); +\tul = $('
        '); +\th2cnt = 0; +\th2li = null; +\th2ol = null; +\th3cnt = 0; +\tcontent.find('h2,h3').each((function(_this) { +\t return function(i, e) { +\t\tvar a, h, id, ish2, li, t; +\t\th = $(e); +\t\tif (h.attr('data-cldoc-dynamic')) { +\t\t return; +\t\t} +\t\tid = h.text(); +\t\tish2 = e.tagName === 'H2'; +\t\tif (ish2) { +\t\t h2cnt += 1; +\t\t t = h2cnt + '. ' + id; +\t\t} else { +\t\t h3cnt += 1; +\t\t t = h2cnt + '.' + h3cnt + '. ' + id; +\t\t} +\t\th.text(t); +\t\th.attr('id', id); +\t\ta = $('', { +\t\t href: _this.make_internal_ref(_this.current_page, id) +\t\t}).text(t); +\t\tli = $('
      1. ').append(a); +\t\tif (!ish2 && h2li !== null) { +\t\t if (h2ol === null) { +\t\t\th2ol = $('
          ').appendTo(h2li); +\t\t } +\t\t return h2ol.append(li); +\t\t} else { +\t\t if (ish2 && h2li === null) { +\t\t\th2li = li; +\t\t\th2ol = null; +\t\t } +\t\t return li.appendTo(ul); +\t\t} +\t }; +\t})(this)); +\tthis.bind_links(ul); +\treturn pagenav.append(ul); }; Page.load_contents = function(page) { - var content, items; - content = $('#cldoc #cldoc_content'); - content.children().detach(); - this.load_description(page, content); - items = $(this.load_items(page)); - content.append(items); - this.bind_links(content); - this.load_pagenav(page, content); - return content.children(); +\tvar content, items; +\tcontent = $('#cldoc #cldoc_content'); +\tcontent.children().detach(); +\tthis.load_description(page, content); +\titems = $(this.load_items(page)); +\tcontent.append(items); +\tthis.bind_links(content); +\tthis.load_pagenav(page, content); +\treturn content.children(); }; Page.push_nav = function(page, scrollto) { - var hash, prevpage, prevscrollto, ref2; - hash = document.location.hash; - ref2 = this.split_ref(this.make_external_ref(hash)), prevpage = ref2[0], prevscrollto = ref2[1]; - return history.pushState({ - page: prevpage, - scrollto: prevscrollto - }, page, this.make_internal_ref(page, scrollto)); +\tvar hash, prevpage, prevscrollto, ref2; +\thash = document.location.hash; +\tref2 = this.split_ref(this.make_external_ref(hash)), prevpage = ref2[0], prevscrollto = ref2[1]; +\treturn history.pushState({ +\t page: prevpage, +\t scrollto: prevscrollto +\t}, page, this.make_internal_ref(page, scrollto)); }; Page.route = function() { - var hash, m, page, route, scrollto; - hash = document.location.hash.substr(1); - route = new RegExp('^([^/]+)(/(.*))?$'); - m = route.exec(hash); - page = ''; - scrollto = ''; - if (!m) { - page = 'index'; - } else { - page = m[1]; - scrollto = m[3]; - } - $(window).on('popstate', (function(_this) { - return function(e) { - var state; - if (e.originalEvent.state) { - state = e.originalEvent.state; - if (state.page !== _this.current_page) { - return _this.load(state.page, state.scrollto, false); - } else { - return _this.select(state.scrollto, false); - } - } - }; - })(this)); - return this.load(page, scrollto); +\tvar hash, m, page, route, scrollto; +\thash = document.location.hash.substr(1); +\troute = new RegExp('^([^/]+)(/(.*))?$'); +\tm = route.exec(hash); +\tpage = ''; +\tscrollto = ''; +\tif (!m) { +\t page = 'index'; +\t} else { +\t page = m[1]; +\t scrollto = m[3]; +\t} +\t$(window).on('popstate', (function(_this) { +\t return function(e) { +\t\tvar state; +\t\tif (e.originalEvent.state) { +\t\t state = e.originalEvent.state; +\t\t if (state.page !== _this.current_page) { +\t\t\treturn _this.load(state.page, state.scrollto, false); +\t\t } else { +\t\t\treturn _this.select(state.scrollto, false); +\t\t } +\t\t} +\t }; +\t})(this)); +\treturn this.load(page, scrollto); }; Page.select = function(scrollto, doanimate) { - var inopts, outopts; - scrollto = $(scrollto); - if (!scrollto && !this.selected_element) { - return; - } - if (scrollto && this.selected_element && scrollto.attr('id') === this.selected_element.attr('id')) { - return; - } - if (doanimate) { - inopts = { - 'duration': 2000, - 'easing': 'easeInOutExpo' - }; - outopts = { - 'duration': 100, - 'easing': 'easeInOutExpo' - }; - } else { - inopts = { - 'duration': 0 - }; - outopts = { - 'duration': 0 - }; - } - if (this.selected_element) { - this.selected_element.removeClass('selected', outopts); - this.selected_element = null; - } - if (scrollto) { - this.selected_element = $(scrollto); - return this.selected_element.addClass('selected', inopts); - } +\tvar inopts, outopts; +\tscrollto = $(scrollto); +\tif (!scrollto && !this.selected_element) { +\t return; +\t} +\tif (scrollto && this.selected_element && scrollto.attr('id') === this.selected_element.attr('id')) { +\t return; +\t} +\tif (doanimate) { +\t inopts = { +\t\t'duration': 2000, +\t\t'easing': 'easeInOutExpo' +\t }; +\t outopts = { +\t\t'duration': 100, +\t\t'easing': 'easeInOutExpo' +\t }; +\t} else { +\t inopts = { +\t\t'duration': 0 +\t }; +\t outopts = { +\t\t'duration': 0 +\t }; +\t} +\tif (this.selected_element) { +\t this.selected_element.removeClass('selected', outopts); +\t this.selected_element = null; +\t} +\tif (scrollto) { +\t this.selected_element = $(scrollto); +\t return this.selected_element.addClass('selected', inopts); +\t} }; Page.scroll = function(page, scrollto, newpage) { - var e, istopandnew, top; - if (!scrollto) { - return; - } - if (page === null) { - page = this.current_page; - } - e = $(document).find('#' + scrollto.replace(/([:() +])/g, '\\$1')).first(); - if (e && e.length > 0) { - e = $(e); - top = e.offset().top - 10; - istopandnew = newpage && e.is('h1'); - if (this.first || istopandnew) { - if (!istopandnew) { - this.select(e); - } else { - this.select(); - } - $('html, body').scrollTop(top); - } else { - this.select(e, true); - $('html, body').animate({ - scrollTop: top - }, 1000, 'easeInOutExpo'); - } - } else { - this.select(null, true); - } - return this.first = false; +\tvar e, istopandnew, top; +\tif (!scrollto) { +\t return; +\t} +\tif (page === null) { +\t page = this.current_page; +\t} +\te = $(document).find('#' + scrollto.replace(/([:() +])/g, '\\$1')).first(); +\tif (e && e.length > 0) { +\t e = $(e); +\t top = e.offset().top - 10; +\t istopandnew = newpage && e.is('h1'); +\t if (this.first || istopandnew) { +\t\tif (!istopandnew) { +\t\t this.select(e); +\t\t} else { +\t\t this.select(); +\t\t} +\t\t$('html, body').scrollTop(top); +\t } else { +\t\tthis.select(e, true); +\t\t$('html, body').animate({ +\t\t scrollTop: top +\t\t}, 1000, 'easeInOutExpo'); +\t } +\t} else { +\t this.select(null, true); +\t} +\treturn this.first = false; }; Page.render_search = function(result) { - var a, content, cpage, data, end, item, j, len, len1, len2, o, p, page, pageid, pageidesc, parts, prev, records, ref2, ref3, ref4, ref5, res, sortfunc, start, t, tag; - content = $('#cldoc_content'); - content.children().detach(); - $('

          Search

          ').append(result.q).appendTo(content); - if (result.records.length === 0) { - $('There were no results for this search query.').appendTo(content); - cldoc.Sidebar.render_search([]); - $('html, body').scrollTop(0); - return; - } - records = []; - ref2 = result.records; - for (j = 0, len = ref2.length; j < len; j++) { - res = ref2[j]; - ref3 = this.split_ref(res.id), page = ref3[0], pageid = ref3[1]; - if (!page in this.pages) { - continue; - } - cpage = this.pages[page]; - data = cpage.xml; - pageidesc = pageid.replace(/([:() ])/g, '\\$1'); - item = data.find('#' + pageidesc); - if (item.length !== 1) { - continue; - } - tag = cldoc.tag(item)[0]; - res.type = tag; - res.brief = new cldoc.Doc(item.children('brief')); - res.page = page; - res.qid = pageid; - records.push(res); - } - sortfunc = function(a, b) { - var ai, bi; - if (a.score !== b.score) { - if (a.score > b.score) { - return -1; - } else { - return 1; - } - } - if (a.type !== b.type) { - ai = cldoc.Node.order[a.type]; - bi = cldoc.Node.order[b.type]; - if (ai !== bi) { - if (ai < bi) { - return -1; - } else { - return 1; - } - } - } - if (a.name < b.name) { - return -1; - } else { - return 1; - } - }; - records.sort(sortfunc); - t = $('').appendTo(content); - for (o = 0, len1 = records.length; o < len1; o++) { - res = records[o]; - res.results.sort(function(a, b) { - if (a[0] !== b[0]) { - if (a[0] < b[0]) { - return -1; - } else { - return 1; - } - } - if (a[1] > b[1]) { - return -1; - } - if (a[1] < b[1]) { - return 1; - } - return 0; - }); - prev = 0; - parts = []; - ref4 = res.results; - for (p = 0, len2 = ref4.length; p < len2; p++) { - ref5 = ref4[p], start = ref5[0], end = ref5[1]; - if (start < prev) { - continue; - } - parts.push(res.qid.substring(prev, start)); - parts.push($('').text(res.qid.substring(start, end))); - prev = end; - } - parts.push(res.qid.substring(prev, res.qid.length)); - a = $('', { - href: this.make_internal_ref(res.id) - }).html(parts); - a.on('click', (function(_this) { - return function(res) { - return function() { - return _this.load_ref(res.id); - }; - }; - })(this)(res)); - $('').append($('').append($(''; - ret += ''; - ret += ''; - ret += ''; - ret += ''; - ret += ''; - ret += ''; - return ret + ''; +\tvar e, ret; +\te = cldoc.html_escape; +\tret = ''; +\tret += ''; +\tret += ''; +\tret += ''; +\tret += ''; +\tret += ''; +\tret += ''; +\treturn ret + ''; }; return Typedef; @@ -1738,18 +1738,18 @@ cldoc.Variable = (function(superClass) { Variable.render_container_tag = 'table'; function Variable(node1) { - this.node = node1; - Variable.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tVariable.__super__.constructor.call(this, this.node); } Variable.prototype.render = function() { - var e, ret; - e = cldoc.html_escape; - ret = ''; - ret += ''; - ret += ''; - ret += ''; - return ret + ''; +\tvar e, ret; +\te = cldoc.html_escape; +\tret = ''; +\tret += ''; +\tret += ''; +\tret += ''; +\treturn ret + ''; }; return Variable; @@ -1764,125 +1764,125 @@ cldoc.Function = (function(superClass) { Function.title = ['Function', 'Functions']; function Function(node1) { - this.node = node1; - Function.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tFunction.__super__.constructor.call(this, this.node); } Function.prototype.identifier_for_display = function() { - return this.name; +\treturn this.name; }; Function.prototype.render_arguments = function() { - var arg, args, argtype, e, i, j, ref2, ret, retu, returntype; - args = this.node.children('argument'); - ret = '
          ').text(res.type)).append($('').html(a)).appendTo(t); - $('
          ')).append($('').html(res.brief.render())).appendTo(t); - } - cldoc.Sidebar.render_search(records); - return $('html, body').scrollTop(0); +\tvar a, content, cpage, data, end, item, j, len, len1, len2, o, p, page, pageid, pageidesc, parts, prev, records, ref2, ref3, ref4, ref5, res, sortfunc, start, t, tag; +\tcontent = $('#cldoc_content'); +\tcontent.children().detach(); +\t$('

          Search

          ').append(result.q).appendTo(content); +\tif (result.records.length === 0) { +\t $('There were no results for this search query.').appendTo(content); +\t cldoc.Sidebar.render_search([]); +\t $('html, body').scrollTop(0); +\t return; +\t} +\trecords = []; +\tref2 = result.records; +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t res = ref2[j]; +\t ref3 = this.split_ref(res.id), page = ref3[0], pageid = ref3[1]; +\t if (!page in this.pages) { +\t\tcontinue; +\t } +\t cpage = this.pages[page]; +\t data = cpage.xml; +\t pageidesc = pageid.replace(/([:() ])/g, '\\$1'); +\t item = data.find('#' + pageidesc); +\t if (item.length !== 1) { +\t\tcontinue; +\t } +\t tag = cldoc.tag(item)[0]; +\t res.type = tag; +\t res.brief = new cldoc.Doc(item.children('brief')); +\t res.page = page; +\t res.qid = pageid; +\t records.push(res); +\t} +\tsortfunc = function(a, b) { +\t var ai, bi; +\t if (a.score !== b.score) { +\t\tif (a.score > b.score) { +\t\t return -1; +\t\t} else { +\t\t return 1; +\t\t} +\t } +\t if (a.type !== b.type) { +\t\tai = cldoc.Node.order[a.type]; +\t\tbi = cldoc.Node.order[b.type]; +\t\tif (ai !== bi) { +\t\t if (ai < bi) { +\t\t\treturn -1; +\t\t } else { +\t\t\treturn 1; +\t\t } +\t\t} +\t } +\t if (a.name < b.name) { +\t\treturn -1; +\t } else { +\t\treturn 1; +\t } +\t}; +\trecords.sort(sortfunc); +\tt = $('').appendTo(content); +\tfor (o = 0, len1 = records.length; o < len1; o++) { +\t res = records[o]; +\t res.results.sort(function(a, b) { +\t\tif (a[0] !== b[0]) { +\t\t if (a[0] < b[0]) { +\t\t\treturn -1; +\t\t } else { +\t\t\treturn 1; +\t\t } +\t\t} +\t\tif (a[1] > b[1]) { +\t\t return -1; +\t\t} +\t\tif (a[1] < b[1]) { +\t\t return 1; +\t\t} +\t\treturn 0; +\t }); +\t prev = 0; +\t parts = []; +\t ref4 = res.results; +\t for (p = 0, len2 = ref4.length; p < len2; p++) { +\t\tref5 = ref4[p], start = ref5[0], end = ref5[1]; +\t\tif (start < prev) { +\t\t continue; +\t\t} +\t\tparts.push(res.qid.substring(prev, start)); +\t\tparts.push($('').text(res.qid.substring(start, end))); +\t\tprev = end; +\t } +\t parts.push(res.qid.substring(prev, res.qid.length)); +\t a = $('', { +\t\thref: this.make_internal_ref(res.id) +\t }).html(parts); +\t a.on('click', (function(_this) { +\t\treturn function(res) { +\t\t return function() { +\t\t\treturn _this.load_ref(res.id); +\t\t }; +\t\t}; +\t })(this)(res)); +\t $('').append($('').append($(''; - if (this.ref) { - id = cldoc.Page.make_link(this.ref, this.identifier_for_display()); - } else { - id = '' + e(this.identifier_for_display()) + ''; - } - ret += ''; - ret += ''; - return ret + ''; +\tvar e, id, ret; +\te = cldoc.html_escape; +\tret = ''; +\tif (this.ref) { +\t id = cldoc.Page.make_link(this.ref, this.identifier_for_display()); +\t} else { +\t id = '' + e(this.identifier_for_display()) + ''; +\t} +\tret += ''; +\tret += ''; +\treturn ret + ''; }; Struct.prototype.render_whole = function() { - var e, id, identifier, isprot, k, ret; - e = cldoc.html_escape; - ret = ''; +\tvar e, id, identifier, isprot, k, ret; +\te = cldoc.html_escape; +\tret = ''; }; Struct.prototype.render_variables = function() { - var container, itemsc, j, len, variable, variables; - variables = this.node.children('variable'); - if (variables.length === 0) { - return ''; - } - container = cldoc.Variable.render_container(); - itemsc = ''; - for (j = 0, len = variables.length; j < len; j++) { - variable = variables[j]; - itemsc += new cldoc.Variable($(variable)).render(); - } - return container[0] + itemsc + container[1]; +\tvar container, itemsc, j, len, variable, variables; +\tvariables = this.node.children('variable'); +\tif (variables.length === 0) { +\t return ''; +\t} +\tcontainer = cldoc.Variable.render_container(); +\titemsc = ''; +\tfor (j = 0, len = variables.length; j < len; j++) { +\t variable = variables[j]; +\t itemsc += new cldoc.Variable($(variable)).render(); +\t} +\treturn container[0] + itemsc + container[1]; }; Struct.prototype.render_fields = function() { - var container, field, fields, itemsc, j, len, tp; - fields = this.node.children('field,union'); - if (fields.length === 0) { - return ''; - } - container = cldoc.Field.render_container(); - itemsc = ''; - for (j = 0, len = fields.length; j < len; j++) { - field = fields[j]; - field = $(field); - tp = cldoc.Page.node_type(field); - if (tp) { - itemsc += new tp(field).render(); - } - } - return container[0] + itemsc + container[1]; +\tvar container, field, fields, itemsc, j, len, tp; +\tfields = this.node.children('field,union'); +\tif (fields.length === 0) { +\t return ''; +\t} +\tcontainer = cldoc.Field.render_container(); +\titemsc = ''; +\tfor (j = 0, len = fields.length; j < len; j++) { +\t field = fields[j]; +\t field = $(field); +\t tp = cldoc.Page.node_type(field); +\t if (tp) { +\t\titemsc += new tp(field).render(); +\t } +\t} +\treturn container[0] + itemsc + container[1]; }; return Struct; @@ -1620,7 +1620,7 @@ cldoc.StructTemplate = (function(superClass) { extend(StructTemplate, superClass); function StructTemplate() { - return StructTemplate.__super__.constructor.apply(this, arguments); +\treturn StructTemplate.__super__.constructor.apply(this, arguments); } return StructTemplate; @@ -1635,9 +1635,9 @@ cldoc.Class = (function(superClass) { Class.title = ['Class', 'Classes']; function Class(node1) { - this.node = node1; - Class.__super__.constructor.call(this, this.node); - this.keyword = 'class'; +\tthis.node = node1; +\tClass.__super__.constructor.call(this, this.node); +\tthis.keyword = 'class'; } return Class; @@ -1650,7 +1650,7 @@ cldoc.ClassTemplate = (function(superClass) { extend(ClassTemplate, superClass); function ClassTemplate() { - return ClassTemplate.__super__.constructor.apply(this, arguments); +\treturn ClassTemplate.__super__.constructor.apply(this, arguments); } return ClassTemplate; @@ -1665,32 +1665,32 @@ cldoc.Namespace = (function(superClass) { Namespace.title = ['Namespace', 'Namespaces']; function Namespace(node1) { - this.node = node1; - Namespace.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tNamespace.__super__.constructor.call(this, this.node); } Namespace.prototype.render = function() { - var a, classes, cls, j, len, ret; - ret = '
          '; - ret += cldoc.Page.make_link(this.ref, this.name, { - 'id': this.id - }); - ret += new cldoc.Doc(this.brief).render(); - classes = this.node.children('class,struct'); - if (classes.length > 0) { - ret += '
          ').text(res.type)).append($('').html(a)).appendTo(t); +\t $('
          ')).append($('').html(res.brief.render())).appendTo(t); +\t} +\tcldoc.Sidebar.render_search(records); +\treturn $('html, body').scrollTop(0); }; Page.search_result = function(result) { - var j, len, page, pageid, pagereqcount, pages, record, ref2, ref3, results1; - pagereqcount = 0; - pages = {}; - ref2 = result.records; - for (j = 0, len = ref2.length; j < len; j++) { - record = ref2[j]; - ref3 = this.split_ref(record.id), page = ref3[0], pageid = ref3[1]; - if (page in pages) { - continue; - } - pagereqcount += 1; - pages[page] = true; - } - if (pagereqcount === 0) { - this.render_search(result); - } - results1 = []; - for (page in pages) { - results1.push(this.request_page(page, (function(_this) { - return function() { - pagereqcount -= 1; - if (pagereqcount === 0) { - return _this.render_search(result); - } - }; - })(this))); - } - return results1; +\tvar j, len, page, pageid, pagereqcount, pages, record, ref2, ref3, results1; +\tpagereqcount = 0; +\tpages = {}; +\tref2 = result.records; +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t record = ref2[j]; +\t ref3 = this.split_ref(record.id), page = ref3[0], pageid = ref3[1]; +\t if (page in pages) { +\t\tcontinue; +\t } +\t pagereqcount += 1; +\t pages[page] = true; +\t} +\tif (pagereqcount === 0) { +\t this.render_search(result); +\t} +\tresults1 = []; +\tfor (page in pages) { +\t results1.push(this.request_page(page, (function(_this) { +\t\treturn function() { +\t\t pagereqcount -= 1; +\t\t if (pagereqcount === 0) { +\t\t\treturn _this.render_search(result); +\t\t } +\t\t}; +\t })(this))); +\t} +\treturn results1; }; Page.search = function(q) { - if (q.length < 3) { - return false; - } - if (!this.search.db) { - this.search.db = new cldoc.SearchDb(); - } - this.search.db.search(q, (function(_this) { - return function(res) { - return _this.search_result(res); - }; - })(this)); - return true; +\tif (q.length < 3) { +\t return false; +\t} +\tif (!this.search.db) { +\t this.search.db = new cldoc.SearchDb(); +\t} +\tthis.search.db.search(q, (function(_this) { +\t return function(res) { +\t\treturn _this.search_result(res); +\t }; +\t})(this)); +\treturn true; }; Page.exit_search = function() { - var ref; - ref = Page.make_external_ref(document.location.hash.substring(1)); - cldoc.Sidebar.exit_search(); - this.current_page = null; - return this.load_ref(ref); +\tvar ref; +\tref = Page.make_external_ref(document.location.hash.substring(1)); +\tcldoc.Sidebar.exit_search(); +\tthis.current_page = null; +\treturn this.load_ref(ref); }; return Page; @@ -799,178 +799,178 @@ cldoc.Sidebar = (function() { function Sidebar() {} Sidebar.init = function() { - var close, div, exitsearch, icon, input, it, items, sidebar; - sidebar = $('#cldoc #cldoc_sidebar'); - if (!sidebar) { - return; - } - items = $('
          ').attr('id', 'cldoc_sidebar_items'); - it = items[0]; - items.on('DOMSubtreeModified', (function(_this) { - return function(e) { - if (it.scrollHeight > it.clientHeight) { - return $(it).removeClass('hide_scrollbar'); - } else { - return $(it).addClass('hide_scrollbar'); - } - }; - })(this)); - sidebar.append(items); - div = $('
          ').attr('id', 'cldoc_search'); - icon = $('
          '); - close = $('
          '); - input = $(''); - items = $().add(div).add(icon).add(close); - input.on('focus', function(e) { - return items.addClass('focus'); - }); - $('body').on('keydown', function(e) { - if (e.altKey && e.keyCode === 83) { - input.focus(); - input.select(); - return true; - } - }); - input.on('blur', function() { - return items.removeClass('focus'); - }); - icon.on('click', function() { - return input.focus(); - }); - exitsearch = function() { - input.val(''); - input.blur(); - return cldoc.Page.exit_search(); - }; - close.on('click', exitsearch); - input.on('keypress', function(e) { - if (e.which === 13) { - cldoc.Page.search(input.val()); - return true; - } - }); - input.on('keydown', function(e) { - if (e.keyCode === 27) { - return exitsearch(); - } - }); - div.append(icon); - div.append(input); - div.append(close); - return sidebar.append(div); +\tvar close, div, exitsearch, icon, input, it, items, sidebar; +\tsidebar = $('#cldoc #cldoc_sidebar'); +\tif (!sidebar) { +\t return; +\t} +\titems = $('
          ').attr('id', 'cldoc_sidebar_items'); +\tit = items[0]; +\titems.on('DOMSubtreeModified', (function(_this) { +\t return function(e) { +\t\tif (it.scrollHeight > it.clientHeight) { +\t\t return $(it).removeClass('hide_scrollbar'); +\t\t} else { +\t\t return $(it).addClass('hide_scrollbar'); +\t\t} +\t }; +\t})(this)); +\tsidebar.append(items); +\tdiv = $('
          ').attr('id', 'cldoc_search'); +\ticon = $('
          '); +\tclose = $('
          '); +\tinput = $(''); +\titems = $().add(div).add(icon).add(close); +\tinput.on('focus', function(e) { +\t return items.addClass('focus'); +\t}); +\t$('body').on('keydown', function(e) { +\t if (e.altKey && e.keyCode === 83) { +\t\tinput.focus(); +\t\tinput.select(); +\t\treturn true; +\t } +\t}); +\tinput.on('blur', function() { +\t return items.removeClass('focus'); +\t}); +\ticon.on('click', function() { +\t return input.focus(); +\t}); +\texitsearch = function() { +\t input.val(''); +\t input.blur(); +\t return cldoc.Page.exit_search(); +\t}; +\tclose.on('click', exitsearch); +\tinput.on('keypress', function(e) { +\t if (e.which === 13) { +\t\tcldoc.Page.search(input.val()); +\t\treturn true; +\t } +\t}); +\tinput.on('keydown', function(e) { +\t if (e.keyCode === 27) { +\t\treturn exitsearch(); +\t } +\t}); +\tdiv.append(icon); +\tdiv.append(input); +\tdiv.append(close); +\treturn sidebar.append(div); }; Sidebar.render_search = function(results) { - return $('#cldoc_sidebar').addClass('search'); +\treturn $('#cldoc_sidebar').addClass('search'); }; Sidebar.exit_search = function() { - return $('#cldoc_sidebar').removeClass('search'); +\treturn $('#cldoc_sidebar').removeClass('search'); }; Sidebar.load_html = function(html) { - var items; - items = $('#cldoc #cldoc_sidebar #cldoc_sidebar_items'); - items.children().detach(); - return items.append(html); +\tvar items; +\titems = $('#cldoc #cldoc_sidebar #cldoc_sidebar_items'); +\titems.children().detach(); +\treturn items.append(html); }; Sidebar.load = function(page) { - var c, div, e, group, head, id, items, j, l, len, ln, name, onpage, parts, ref2; - items = $('#cldoc #cldoc_sidebar #cldoc_sidebar_items'); - e = cldoc.html_escape; - if (items.length === 0) { - return null; - } - items.children().detach(); - head = cldoc.Page.make_header(page); - if (head) { - div = '
          '; - div += head; - id = page.attr('id'); - parts = id.split('::'); - l = parts.slice(0, parts.length - 1).join('::'); - name = ' '; - if (parts.length === 1) { - name += 'Index'; - } else { - name += '' + e(parts[parts.length - 2]) + ''; - } - ln = cldoc.Page.make_internal_ref(l); - div += '
          ' + name + '
          '; - items.append($(div)); - } - items.append($('
          ')); - onpage = page.children(); - c = ''; - ref2 = cldoc.Node.groups; - for (j = 0, len = ref2.length; j < len; j++) { - group = ref2[j]; - c += this.load_group(page, onpage.filter(group)); - } - items.append($(c)); - cldoc.Page.bind_links(items); - return $('#cldoc_sidebar_items').children(); +\tvar c, div, e, group, head, id, items, j, l, len, ln, name, onpage, parts, ref2; +\titems = $('#cldoc #cldoc_sidebar #cldoc_sidebar_items'); +\te = cldoc.html_escape; +\tif (items.length === 0) { +\t return null; +\t} +\titems.children().detach(); +\thead = cldoc.Page.make_header(page); +\tif (head) { +\t div = '
          '; +\t div += head; +\t id = page.attr('id'); +\t parts = id.split('::'); +\t l = parts.slice(0, parts.length - 1).join('::'); +\t name = ' '; +\t if (parts.length === 1) { +\t\tname += 'Index'; +\t } else { +\t\tname += '' + e(parts[parts.length - 2]) + ''; +\t } +\t ln = cldoc.Page.make_internal_ref(l); +\t div += '
          ' + name + '
          '; +\t items.append($(div)); +\t} +\titems.append($('
          ')); +\tonpage = page.children(); +\tc = ''; +\tref2 = cldoc.Node.groups; +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t group = ref2[j]; +\t c += this.load_group(page, onpage.filter(group)); +\t} +\titems.append($(c)); +\tcldoc.Page.bind_links(items); +\treturn $('#cldoc_sidebar_items').children(); }; Sidebar.load_group = function(page, items) { - var brief, e, ftag, isprot, isstat, isvirt, item, j, len, nm, ret, tp, type; - if (items.length === 0) { - return ''; - } - ftag = cldoc.tag($(items[0]))[0]; - type = cldoc.Page.node_type(items); - if (!type) { - return ''; - } - e = cldoc.html_escape; - ret = '
          ' + e(type.title[1]) + '
          '; - ret += '
            '; - for (j = 0, len = items.length; j < len; j++) { - item = items[j]; - item = $(item); - if (cldoc.tag(item)[0] !== ftag) { - tp = cldoc.Page.node_type(item); - } else { - tp = type; - } - if (!tp) { - continue; - } - item = new tp(item); - if ('render_sidebar' in item) { - ret += item.render_sidebar(); - continue; - } - ret += '
          • '; - nm = item.sidebar_name(); - if (item.ref) { - href = cldoc.Page.make_internal_ref(item.ref); - } else { - href = cldoc.Page.make_internal_ref(cldoc.Page.current_page, item.id); - } - ret += '' + e(nm) + ''; - isvirt = item.node.attr('virtual'); - isprot = item.node.attr('access') === 'protected'; - isstat = item.node.attr('static'); - if (isprot && isvirt) { - ret += 'p v'; - } else if (isprot && isstat) { - ret += 's p'; - } else if (isprot) { - ret += 'p'; - } else if (isstat) { - ret += 's'; - } else if (isvirt) { - ret += 'v'; - } - brief = new cldoc.Doc(item.brief).render(); - if (brief) { - ret += brief; - } - ret += '
          • '; - } - return ret + '
          '; +\tvar brief, e, ftag, isprot, isstat, isvirt, item, j, len, nm, ret, tp, type; +\tif (items.length === 0) { +\t return ''; +\t} +\tftag = cldoc.tag($(items[0]))[0]; +\ttype = cldoc.Page.node_type(items); +\tif (!type) { +\t return ''; +\t} +\te = cldoc.html_escape; +\tret = '
          ' + e(type.title[1]) + '
          '; +\tret += '
            '; +\tfor (j = 0, len = items.length; j < len; j++) { +\t item = items[j]; +\t item = $(item); +\t if (cldoc.tag(item)[0] !== ftag) { +\t\ttp = cldoc.Page.node_type(item); +\t } else { +\t\ttp = type; +\t } +\t if (!tp) { +\t\tcontinue; +\t } +\t item = new tp(item); +\t if ('render_sidebar' in item) { +\t\tret += item.render_sidebar(); +\t\tcontinue; +\t } +\t ret += '
          • '; +\t nm = item.sidebar_name(); +\t if (item.ref) { +\t\thref = cldoc.Page.make_internal_ref(item.ref); +\t } else { +\t\thref = cldoc.Page.make_internal_ref(cldoc.Page.current_page, item.id); +\t } +\t ret += '' + e(nm) + ''; +\t isvirt = item.node.attr('virtual'); +\t isprot = item.node.attr('access') === 'protected'; +\t isstat = item.node.attr('static'); +\t if (isprot && isvirt) { +\t\tret += 'p v'; +\t } else if (isprot && isstat) { +\t\tret += 's p'; +\t } else if (isprot) { +\t\tret += 'p'; +\t } else if (isstat) { +\t\tret += 's'; +\t } else if (isvirt) { +\t\tret += 'v'; +\t } +\t brief = new cldoc.Doc(item.brief).render(); +\t if (brief) { +\t\tret += brief; +\t } +\t ret += '
          • '; +\t} +\treturn ret + '
          '; }; return Sidebar; @@ -981,8 +981,8 @@ cldoc.Mixin = function() { var base, j, mixin, mixins; base = arguments[0], mixins = 2 <= arguments.length ? slice.call(arguments, 1) : []; for (j = mixins.length - 1; j >= 0; j += -1) { - mixin = mixins[j]; - base = mixin(base); +\tmixin = mixins[j]; +\tbase = mixin(base); } return base; }; @@ -993,71 +993,71 @@ cldoc.Node = (function() { Node.groups = ['coverage', 'arguments', 'references', 'category', 'namespace', 'templatetypeparameter, templatenontypeparameter', 'base', 'implements', 'subclass', 'implementedby', 'typedef', 'class, classtemplate', 'gobject\\:class', 'gobject\\:interface', 'gobject\\:boxed', 'struct, structtemplate', 'enum', 'field, union', 'variable', 'gobject\\:property', 'constructor', 'destructor', 'method, methodtemplate', 'function, functiontemplate', 'report']; Node.order = { - 'category': 0, - 'namespace': 1, - 'templatetypeparameter': 2, - 'templatenontypeparameter': 2, - 'base': 3, - 'implements': 3, - 'subclass': 4, - 'implementedby': 4, - 'typedef': 5, - 'class': 6, - 'classtemplate': 6, - 'gobjectclass': 6, - 'gobjectinterface': 7, - 'struct': 8, - 'structtemplate': 8, - 'gobjectboxed': 8, - 'enum': 9, - 'enumvalue': 10, - 'field': 11, - 'union': 12, - 'variable': 13, - 'gobjectproperty': 13, - 'constructor': 14, - 'destructor': 15, - 'method': 16, - 'methodtemplate': 16, - 'function': 17, - 'functiontemplate': 17 +\t'category': 0, +\t'namespace': 1, +\t'templatetypeparameter': 2, +\t'templatenontypeparameter': 2, +\t'base': 3, +\t'implements': 3, +\t'subclass': 4, +\t'implementedby': 4, +\t'typedef': 5, +\t'class': 6, +\t'classtemplate': 6, +\t'gobjectclass': 6, +\t'gobjectinterface': 7, +\t'struct': 8, +\t'structtemplate': 8, +\t'gobjectboxed': 8, +\t'enum': 9, +\t'enumvalue': 10, +\t'field': 11, +\t'union': 12, +\t'variable': 13, +\t'gobjectproperty': 13, +\t'constructor': 14, +\t'destructor': 15, +\t'method': 16, +\t'methodtemplate': 16, +\t'function': 17, +\t'functiontemplate': 17 }; Node.render_container_tag = 'div'; function Node(node1) { - this.node = node1; - if (!this.node) { - return; - } - if (this.node.length === 0) { - this.node = null; - return; - } - this.name = this.node.attr('name'); - this.id = this.node.attr('id'); - this.ref = this.node.attr('ref'); - if (this.ref && !this.id) { - this.id = this.ref.replace('#', '+'); - } - this.brief = this.node.children('brief').first(); - this.doc = this.node.children('doc').first(); +\tthis.node = node1; +\tif (!this.node) { +\t return; +\t} +\tif (this.node.length === 0) { +\t this.node = null; +\t return; +\t} +\tthis.name = this.node.attr('name'); +\tthis.id = this.node.attr('id'); +\tthis.ref = this.node.attr('ref'); +\tif (this.ref && !this.id) { +\t this.id = this.ref.replace('#', '+'); +\t} +\tthis.brief = this.node.children('brief').first(); +\tthis.doc = this.node.children('doc').first(); } Node.prototype.full_name_for_display = function() { - return null; +\treturn null; }; Node.prototype.sidebar_name = function() { - return this.name; +\treturn this.name; }; Node.render_container = function() { - return ['<' + this.render_container_tag + ' class="' + cldoc.html_escape(this.title[1].toLowerCase().replace(/[ ]/g, '_')) + '">', '']; +\treturn ['<' + this.render_container_tag + ' class="' + cldoc.html_escape(this.title[1].toLowerCase().replace(/[ ]/g, '_')) + '">', '']; }; Node.prototype.render = function() { - return null; +\treturn null; }; return Node; @@ -1068,134 +1068,134 @@ cldoc.Type = (function(superClass) { extend(Type, superClass); function Type(node1) { - var a, arg, args, builtincls, e, i, j, len, len1, name, o, result, subtype; - this.node = node1; - Type.__super__.constructor.call(this, this.node); - this.qualifier = this.node.attr('qualifier'); - this.size = this.node.attr('size'); - this.transfer_ownership = this.node.attr('transfer-ownership') || 'none'; - this.allow_none = this.node.attr('allow-none') === 'yes'; - this.typeparts = []; - this.typeparts_text = []; - subtype = this.node.children('type'); - e = cldoc.html_escape; - if (subtype.length > 0) { - this.subtype = this.append_type(subtype); - } - if (this.node.attr('class') === 'function') { - this.typeparts.push(''); - this.typeparts_text.push(''); - result = this.node.children('result').first(); - args = this.node.children('arguments').first().children('type'); - this.result = this.append_type($(result)); - this.args = []; - this.typeparts.push(''); - this.typeparts_text.push(''); - this.append_plain_part('('); - this.append_qualifier(); - this.append_plain_part(')'); - this.typeparts.push(''); - this.typeparts_text.push(''); - this.append_plain_part('('); - for (i = j = 0, len = args.length; j < len; i = ++j) { - arg = args[i]; - if (i !== 0) { - this.append_plain_part(', '); - } - this.args.push(this.append_type($(arg))); - } - this.append_plain_part(')'); - this.typeparts.push(''); - this.typeparts_text.push(''); - } else if (this.node.attr('class') === 'template') { - this.typeparts.push(''); - this.typeparts_text.push(''); - if (this.ref) { - a = cldoc.Page.make_link(this.ref, this.name); - name = '' + a + ''; - } else { - name = '' + e(this.name) + ''; - } - this.typeparts.push(name); - this.typeparts_text.push(this.name); - this.typeparts.push(''); - this.typeparts_text.push(''); - this.append_plain_part('<'); - args = this.node.children('template-arguments').first().children('type'); - this.args = []; - for (i = o = 0, len1 = args.length; o < len1; i = ++o) { - arg = args[i]; - if (i !== 0) { - this.append_plain_part(', '); - } - this.args.push(this.append_type($(arg))); - } - this.append_plain_part('>'); - this.typeparts.push(''); - this.typeparts_text.push(''); - } else { - if (this.name) { - if (this.node.attr('builtin')) { - builtincls = 'builtin'; - } else { - builtincls = ''; - } - if (this.ref) { - a = cldoc.Page.make_link(this.ref, this.name); - name = '' + a + ''; - } else { - name = '' + e(this.name) + ''; - } - this.typeparts.push(name); - this.typeparts_text.push(this.name); - } - this.append_qualifier(); - } - if (this.size) { - this.typeparts.push('' + '[' + this.size + ']' + ''); - this.typeparts_text.push('[' + this.size + ']'); - } +\tvar a, arg, args, builtincls, e, i, j, len, len1, name, o, result, subtype; +\tthis.node = node1; +\tType.__super__.constructor.call(this, this.node); +\tthis.qualifier = this.node.attr('qualifier'); +\tthis.size = this.node.attr('size'); +\tthis.transfer_ownership = this.node.attr('transfer-ownership') || 'none'; +\tthis.allow_none = this.node.attr('allow-none') === 'yes'; +\tthis.typeparts = []; +\tthis.typeparts_text = []; +\tsubtype = this.node.children('type'); +\te = cldoc.html_escape; +\tif (subtype.length > 0) { +\t this.subtype = this.append_type(subtype); +\t} +\tif (this.node.attr('class') === 'function') { +\t this.typeparts.push(''); +\t this.typeparts_text.push(''); +\t result = this.node.children('result').first(); +\t args = this.node.children('arguments').first().children('type'); +\t this.result = this.append_type($(result)); +\t this.args = []; +\t this.typeparts.push(''); +\t this.typeparts_text.push(''); +\t this.append_plain_part('('); +\t this.append_qualifier(); +\t this.append_plain_part(')'); +\t this.typeparts.push(''); +\t this.typeparts_text.push(''); +\t this.append_plain_part('('); +\t for (i = j = 0, len = args.length; j < len; i = ++j) { +\t\targ = args[i]; +\t\tif (i !== 0) { +\t\t this.append_plain_part(', '); +\t\t} +\t\tthis.args.push(this.append_type($(arg))); +\t } +\t this.append_plain_part(')'); +\t this.typeparts.push(''); +\t this.typeparts_text.push(''); +\t} else if (this.node.attr('class') === 'template') { +\t this.typeparts.push(''); +\t this.typeparts_text.push(''); +\t if (this.ref) { +\t\ta = cldoc.Page.make_link(this.ref, this.name); +\t\tname = '' + a + ''; +\t } else { +\t\tname = '' + e(this.name) + ''; +\t } +\t this.typeparts.push(name); +\t this.typeparts_text.push(this.name); +\t this.typeparts.push(''); +\t this.typeparts_text.push(''); +\t this.append_plain_part('<'); +\t args = this.node.children('template-arguments').first().children('type'); +\t this.args = []; +\t for (i = o = 0, len1 = args.length; o < len1; i = ++o) { +\t\targ = args[i]; +\t\tif (i !== 0) { +\t\t this.append_plain_part(', '); +\t\t} +\t\tthis.args.push(this.append_type($(arg))); +\t } +\t this.append_plain_part('>'); +\t this.typeparts.push(''); +\t this.typeparts_text.push(''); +\t} else { +\t if (this.name) { +\t\tif (this.node.attr('builtin')) { +\t\t builtincls = 'builtin'; +\t\t} else { +\t\t builtincls = ''; +\t\t} +\t\tif (this.ref) { +\t\t a = cldoc.Page.make_link(this.ref, this.name); +\t\t name = '' + a + ''; +\t\t} else { +\t\t name = '' + e(this.name) + ''; +\t\t} +\t\tthis.typeparts.push(name); +\t\tthis.typeparts_text.push(this.name); +\t } +\t this.append_qualifier(); +\t} +\tif (this.size) { +\t this.typeparts.push('' + '[' + this.size + ']' + ''); +\t this.typeparts_text.push('[' + this.size + ']'); +\t} } Type.prototype.as_text = function() { - return this.typeparts_text.join(''); +\treturn this.typeparts_text.join(''); }; Type.prototype.render = function() { - var item, j, len, ref2, ret; - ret = ''; - ref2 = this.typeparts; - for (j = 0, len = ref2.length; j < len; j++) { - item = ref2[j]; - ret += item; - } - return ret; +\tvar item, j, len, ref2, ret; +\tret = ''; +\tref2 = this.typeparts; +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t item = ref2[j]; +\t ret += item; +\t} +\treturn ret; }; Type.prototype.append_type = function(type) { - type = new Type(type); - this.typeparts.push(''); - this.typeparts_text.push(''); - this.typeparts = this.typeparts.concat(type.typeparts); - this.typeparts_text = this.typeparts_text.concat(type.typeparts_text); - this.typeparts.push(''); - this.typeparts_text.push(''); - return type; +\ttype = new Type(type); +\tthis.typeparts.push(''); +\tthis.typeparts_text.push(''); +\tthis.typeparts = this.typeparts.concat(type.typeparts); +\tthis.typeparts_text = this.typeparts_text.concat(type.typeparts_text); +\tthis.typeparts.push(''); +\tthis.typeparts_text.push(''); +\treturn type; }; Type.prototype.append_plain_part = function(text) { - this.typeparts.push('' + cldoc.html_escape(text) + ''); - return this.typeparts_text.push(text); +\tthis.typeparts.push('' + cldoc.html_escape(text) + ''); +\treturn this.typeparts_text.push(text); }; Type.prototype.append_qualifier = function() { - var q, qc; - if (this.qualifier) { - qc = cldoc.html_escape(this.qualifier).replace(/const/g, 'const'); - q = ' ' + qc + ''; - this.typeparts.push(q); - return this.typeparts_text.push(this.qualifier); - } +\tvar q, qc; +\tif (this.qualifier) { +\t qc = cldoc.html_escape(this.qualifier).replace(/const/g, 'const'); +\t q = ' ' + qc + ''; +\t this.typeparts.push(q); +\t return this.typeparts_text.push(this.qualifier); +\t} }; return Type; @@ -1210,126 +1210,126 @@ cldoc.Doc = (function(superClass) { Doc.magic_separator = '%~@@~%'; Doc.init = function() { - var origproto; - origproto = marked.InlineLexer.prototype.outputLink; - return marked.InlineLexer.prototype.outputLink = function(cap, link) { - var orighref, ret; - orighref = link.href; - if (link.href.match(/^[a-z]+:/) === null && link.href[0] !== '/') { - link.href = cldoc.host + '/' + link.href; - } - ret = origproto.call(this, cap, link); - link.href = orighref; - return ret; - }; +\tvar origproto; +\torigproto = marked.InlineLexer.prototype.outputLink; +\treturn marked.InlineLexer.prototype.outputLink = function(cap, link) { +\t var orighref, ret; +\t orighref = link.href; +\t if (link.href.match(/^[a-z]+:/) === null && link.href[0] !== '/') { +\t\tlink.href = cldoc.host + '/' + link.href; +\t } +\t ret = origproto.call(this, cap, link); +\t link.href = orighref; +\t return ret; +\t}; }; function Doc(node1) { - this.node = node1; - Doc.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tDoc.__super__.constructor.call(this, this.node); } Doc.either = function(node) { - var brief, doc; - doc = this.doc(node); - if (doc) { - return doc; - } - brief = this.brief(node); - if (brief) { - return brief; - } - return ''; +\tvar brief, doc; +\tdoc = this.doc(node); +\tif (doc) { +\t return doc; +\t} +\tbrief = this.brief(node); +\tif (brief) { +\t return brief; +\t} +\treturn ''; }; Doc.brief = function(node) { - return new Doc(node.children('brief')).render(); +\treturn new Doc(node.children('brief')).render(); }; Doc.doc = function(node) { - return new Doc(node.children('doc')).render(); +\treturn new Doc(node.children('doc')).render(); }; Doc.prototype.escape = function(text) { - var r; - r = /([*_\\`{}#+-.!\[\]])/g; - return text.replace(r, function(m) { - return "\\" + m; - }); +\tvar r; +\tr = /([*_\\`{}#+-.!\[\]])/g; +\treturn text.replace(r, function(m) { +\t return "\\" + m; +\t}); }; Doc.prototype.process_markdown = function(text) { - var a, html, i, j, marked_options, parts, ref2, rethtml; - marked_options = { - highlight: function(code) { - return hljs.highlightAuto(code).value; - } - }; - marked.setOptions(marked_options); - html = marked(text); - parts = html.split(Doc.magic_separator); - rethtml = ''; - for (i = j = 0, ref2 = parts.length - 2; j <= ref2; i = j += 3) { - a = cldoc.Page.make_link(parts[i + 1], parts[i + 2]); - rethtml += parts[i] + a; - } - return rethtml + parts[parts.length - 1]; +\tvar a, html, i, j, marked_options, parts, ref2, rethtml; +\tmarked_options = { +\t highlight: function(code) { +\t\treturn hljs.highlightAuto(code).value; +\t } +\t}; +\tmarked.setOptions(marked_options); +\thtml = marked(text); +\tparts = html.split(Doc.magic_separator); +\trethtml = ''; +\tfor (i = j = 0, ref2 = parts.length - 2; j <= ref2; i = j += 3) { +\t a = cldoc.Page.make_link(parts[i + 1], parts[i + 2]); +\t rethtml += parts[i] + a; +\t} +\treturn rethtml + parts[parts.length - 1]; }; Doc.prototype.process_code = function(code) { - var c, e, j, len, ref2, ret, tag; - ret = '
          ';
          -    e = cldoc.html_escape;
          -    ref2 = $(code).contents();
          -    for (j = 0, len = ref2.length; j < len; j++) {
          -      c = ref2[j];
          -      if (c.nodeType === document.ELEMENT_NODE) {
          -        tag = c.tagName.toLowerCase();
          -        c = $(c);
          -        if (tag === 'ref') {
          -          ret += cldoc.Page.make_link(c.attr('ref'), c.attr('name'));
          -        } else {
          -          ret += '' + e(c.text()) + '';
          -        }
          -      } else {
          -        ret += e($(c).text());
          -      }
          -    }
          -    return ret + '
          '; +\tvar c, e, j, len, ref2, ret, tag; +\tret = '
          ';
          +\te = cldoc.html_escape;
          +\tref2 = $(code).contents();
          +\tfor (j = 0, len = ref2.length; j < len; j++) {
          +\t  c = ref2[j];
          +\t  if (c.nodeType === document.ELEMENT_NODE) {
          +\t\ttag = c.tagName.toLowerCase();
          +\t\tc = $(c);
          +\t\tif (tag === 'ref') {
          +\t\t  ret += cldoc.Page.make_link(c.attr('ref'), c.attr('name'));
          +\t\t} else {
          +\t\t  ret += '' + e(c.text()) + '';
          +\t\t}
          +\t  } else {
          +\t\tret += e($(c).text());
          +\t  }
          +\t}
          +\treturn ret + '
          '; }; Doc.prototype.render = function() { - var astext, c, contents, e, j, len, msep, ret, tag; - if (!this.node) { - return ''; - } - e = cldoc.html_escape; - ret = '
          '; - contents = this.node.contents(); - astext = ''; - msep = Doc.magic_separator; - for (j = 0, len = contents.length; j < len; j++) { - c = contents[j]; - if (c.nodeType === document.ELEMENT_NODE) { - tag = c.tagName.toLowerCase(); - if (tag === 'ref') { - c = $(c); - astext += this.escape(msep + c.attr('ref') + msep + c.text() + msep); - } else if (tag === 'code') { - if (astext) { - ret += this.process_markdown(astext); - astext = ''; - } - ret += this.process_code(c); - } - } else { - astext += $(c).text(); - } - } - if (astext) { - ret += this.process_markdown(astext); - } - return ret + '
          '; +\tvar astext, c, contents, e, j, len, msep, ret, tag; +\tif (!this.node) { +\t return ''; +\t} +\te = cldoc.html_escape; +\tret = '
          '; +\tcontents = this.node.contents(); +\tastext = ''; +\tmsep = Doc.magic_separator; +\tfor (j = 0, len = contents.length; j < len; j++) { +\t c = contents[j]; +\t if (c.nodeType === document.ELEMENT_NODE) { +\t\ttag = c.tagName.toLowerCase(); +\t\tif (tag === 'ref') { +\t\t c = $(c); +\t\t astext += this.escape(msep + c.attr('ref') + msep + c.text() + msep); +\t\t} else if (tag === 'code') { +\t\t if (astext) { +\t\t\tret += this.process_markdown(astext); +\t\t\tastext = ''; +\t\t } +\t\t ret += this.process_code(c); +\t\t} +\t } else { +\t\tastext += $(c).text(); +\t } +\t} +\tif (astext) { +\t ret += this.process_markdown(astext); +\t} +\treturn ret + '
          '; }; return Doc; @@ -1344,34 +1344,34 @@ cldoc.Category = (function(superClass) { Category.title = ['', 'Categories']; function Category(node1) { - this.node = node1; - Category.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tCategory.__super__.constructor.call(this, this.node); } Category.prototype.full_name_for_display = function() { - return this.name; +\treturn this.name; }; Category.prototype.render = function() { - var a, cat, categories, doc, j, len, ret; - ret = '
          '; - ret += cldoc.Page.make_link(this.ref, this.name, { - 'id': this.id - }); - ret += new cldoc.Doc(this.brief).render(); - categories = this.node.children('category'); - if (categories.length > 0) { - ret += ''; - for (j = 0, len = categories.length; j < len; j++) { - cat = categories[j]; - cat = $(cat); - a = cldoc.Page.make_link(cat.attr('ref'), cat.attr('name')); - doc = cldoc.Doc.either(cat); - ret += ''; - } - ret += '
          ' + a + '' + doc + '
          '; - } - return ret; +\tvar a, cat, categories, doc, j, len, ret; +\tret = '
          '; +\tret += cldoc.Page.make_link(this.ref, this.name, { +\t 'id': this.id +\t}); +\tret += new cldoc.Doc(this.brief).render(); +\tcategories = this.node.children('category'); +\tif (categories.length > 0) { +\t ret += ''; +\t for (j = 0, len = categories.length; j < len; j++) { +\t\tcat = categories[j]; +\t\tcat = $(cat); +\t\ta = cldoc.Page.make_link(cat.attr('ref'), cat.attr('name')); +\t\tdoc = cldoc.Doc.either(cat); +\t\tret += ''; +\t } +\t ret += '
          ' + a + '' + doc + '
          '; +\t} +\treturn ret; }; return Category; @@ -1386,44 +1386,44 @@ cldoc.Enum = (function(superClass) { Enum.title = ['Enum', 'Enumerations']; function Enum(node1) { - this.node = node1; - Enum.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tEnum.__super__.constructor.call(this, this.node); } Enum.prototype.render = function() { - var e, isprot, j, len, n, ref2, ret, value; - e = cldoc.html_escape; - isprot = this.node.attr('access') === 'protected'; - if (isprot) { - n = 'protected enum'; - } else { - n = 'enum'; - } - if (this.node.attr('class')) { - n += ' class'; - } - if (this.node.attr('typedef')) { - n = 'typedef ' + n; - } - ret = '
          ' + e(n) + ' '; - ret += ''; - if (!cldoc.startswith(this.name, '(anonymous')) { - ret += e(this.name); - } - ret += '
          '; - ret += cldoc.Doc.either(this.node); - ret += ''; - ref2 = this.node.children('enumvalue'); - for (j = 0, len = ref2.length; j < len; j++) { - value = ref2[j]; - value = $(value); - ret += ''; - ret += ''; - ret += ''; - ret += ''; - ret += ''; - } - return ret + '
          ' + e(value.attr('name')) + '' + e(value.attr('value')) + '' + cldoc.Doc.either(value) + '
          '; +\tvar e, isprot, j, len, n, ref2, ret, value; +\te = cldoc.html_escape; +\tisprot = this.node.attr('access') === 'protected'; +\tif (isprot) { +\t n = 'protected enum'; +\t} else { +\t n = 'enum'; +\t} +\tif (this.node.attr('class')) { +\t n += ' class'; +\t} +\tif (this.node.attr('typedef')) { +\t n = 'typedef ' + n; +\t} +\tret = '
          ' + e(n) + ' '; +\tret += ''; +\tif (!cldoc.startswith(this.name, '(anonymous')) { +\t ret += e(this.name); +\t} +\tret += '
          '; +\tret += cldoc.Doc.either(this.node); +\tret += ''; +\tref2 = this.node.children('enumvalue'); +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t value = ref2[j]; +\t value = $(value); +\t ret += ''; +\t ret += ''; +\t ret += ''; +\t ret += ''; +\t ret += ''; +\t} +\treturn ret + '
          ' + e(value.attr('name')) + '' + e(value.attr('value')) + '' + cldoc.Doc.either(value) + '
          '; }; return Enum; @@ -1435,77 +1435,77 @@ cldoc.Node.types["enum"] = cldoc.Enum; cldoc.Templated = function(base) { var MixedIn; MixedIn = (function(superClass) { - extend(MixedIn, superClass); - - function MixedIn() { - return MixedIn.__super__.constructor.apply(this, arguments); - } - - MixedIn.prototype.template_parameter_name = function(param) { - var def, name, ret, tp; - param = $(param); - name = param.attr('name'); - def = param.attr('default'); - tp = param.children('type'); - ret = ''; - if (tp.length > 0) { - ret += (new cldoc.Type(tp)).as_text() + ' '; - } - ret += name; - if (def) { - ret += ' = ' + def; - } - return ret; - }; - - MixedIn.prototype.templated_name = function() { - var name, x; - name = this.name; - name += '<'; - name += ((function() { - var j, len, ref2, results1; - ref2 = this.node.children('templatetypeparameter, templatenontypeparameter'); - results1 = []; - for (j = 0, len = ref2.length; j < len; j++) { - x = ref2[j]; - results1.push(this.template_parameter_name(x)); - } - return results1; - }).call(this)).join(', '); - name += '>'; - return name; - }; - - MixedIn.prototype.identifier_for_display = function() { - return this.templated_name(); - }; - - MixedIn.prototype.full_name_for_display = function() { - return this.templated_name(); - }; - - MixedIn.prototype.sidebar_name = function() { - return this.identifier_for_display(); - }; - - MixedIn.prototype.render_arguments = function() { - var j, len, ret, tt, x; - ret = ''; - tt = this.node.children('templatetypeparameter, templatenontypeparameter'); - for (j = 0, len = tt.length; j < len; j++) { - x = tt[j]; - x = $(x); - ret += ''; - ret += ''; - ret += ''; - ret += ''; - } - ret += '
          ' + x.attr('name') + '' + cldoc.Doc.either(x) + '
          '; - ret += MixedIn.__super__.render_arguments.apply(this, arguments); - return ret; - }; - - return MixedIn; +\textend(MixedIn, superClass); + +\tfunction MixedIn() { +\t return MixedIn.__super__.constructor.apply(this, arguments); +\t} + +\tMixedIn.prototype.template_parameter_name = function(param) { +\t var def, name, ret, tp; +\t param = $(param); +\t name = param.attr('name'); +\t def = param.attr('default'); +\t tp = param.children('type'); +\t ret = ''; +\t if (tp.length > 0) { +\t\tret += (new cldoc.Type(tp)).as_text() + ' '; +\t } +\t ret += name; +\t if (def) { +\t\tret += ' = ' + def; +\t } +\t return ret; +\t}; + +\tMixedIn.prototype.templated_name = function() { +\t var name, x; +\t name = this.name; +\t name += '<'; +\t name += ((function() { +\t\tvar j, len, ref2, results1; +\t\tref2 = this.node.children('templatetypeparameter, templatenontypeparameter'); +\t\tresults1 = []; +\t\tfor (j = 0, len = ref2.length; j < len; j++) { +\t\t x = ref2[j]; +\t\t results1.push(this.template_parameter_name(x)); +\t\t} +\t\treturn results1; +\t }).call(this)).join(', '); +\t name += '>'; +\t return name; +\t}; + +\tMixedIn.prototype.identifier_for_display = function() { +\t return this.templated_name(); +\t}; + +\tMixedIn.prototype.full_name_for_display = function() { +\t return this.templated_name(); +\t}; + +\tMixedIn.prototype.sidebar_name = function() { +\t return this.identifier_for_display(); +\t}; + +\tMixedIn.prototype.render_arguments = function() { +\t var j, len, ret, tt, x; +\t ret = ''; +\t tt = this.node.children('templatetypeparameter, templatenontypeparameter'); +\t for (j = 0, len = tt.length; j < len; j++) { +\t\tx = tt[j]; +\t\tx = $(x); +\t\tret += ''; +\t\tret += ''; +\t\tret += ''; +\t\tret += ''; +\t } +\t ret += '
          ' + x.attr('name') + '' + cldoc.Doc.either(x) + '
          '; +\t ret += MixedIn.__super__.render_arguments.apply(this, arguments); +\t return ret; +\t}; + +\treturn MixedIn; })(base); return MixedIn; @@ -1519,95 +1519,95 @@ cldoc.Struct = (function(superClass) { Struct.render_container_tag = 'table'; function Struct(node1) { - this.node = node1; - Struct.__super__.constructor.call(this, this.node); - if (this.node.attr('typedef')) { - this.keyword = 'typedef struct'; - } else { - this.keyword = 'struct'; - } +\tthis.node = node1; +\tStruct.__super__.constructor.call(this, this.node); +\tif (this.node.attr('typedef')) { +\t this.keyword = 'typedef struct'; +\t} else { +\t this.keyword = 'struct'; +\t} } Struct.prototype.render = function() { - if (this.ref || this.node.children('field, method, function, methodtemplate, functiontemplate').length === 0) { - return this.render_short(); - } else { - return this.render_whole(); - } +\tif (this.ref || this.node.children('field, method, function, methodtemplate, functiontemplate').length === 0) { +\t return this.render_short(); +\t} else { +\t return this.render_whole(); +\t} }; Struct.prototype.identifier_for_display = function() { - return this.name; +\treturn this.name; }; Struct.prototype.render_short = function() { - var e, id, ret; - e = cldoc.html_escape; - ret = '
          ' + id + '' + cldoc.Doc.brief(this.node) + '
          ' + id + '' + cldoc.Doc.brief(this.node) + '
          '; - identifier = this.identifier_for_display(); - id = '' + e(identifier) + ''; - k = ''; - isprot = this.node.attr('access') === 'protected'; - if (isprot) { - k += 'protected '; - } - k += e(this.keyword) + ''; - if (this.node.attr('anonymous') !== 'yes') { - k += ' ' + id; - } - ret += '
          ' + k + '
          '; - ret += cldoc.Doc.either(this.node); - ret += this.render_fields(); - ret += this.render_variables(); - return ret + '
          '; +\tidentifier = this.identifier_for_display(); +\tid = '' + e(identifier) + ''; +\tk = ''; +\tisprot = this.node.attr('access') === 'protected'; +\tif (isprot) { +\t k += 'protected '; +\t} +\tk += e(this.keyword) + ''; +\tif (this.node.attr('anonymous') !== 'yes') { +\t k += ' ' + id; +\t} +\tret += '
          ' + k + '
          '; +\tret += cldoc.Doc.either(this.node); +\tret += this.render_fields(); +\tret += this.render_variables(); +\treturn ret + '
          '; - for (j = 0, len = classes.length; j < len; j++) { - cls = classes[j]; - cls = $(cls); - ret += ''; - a = cldoc.Page.make_link(cls.attr('ref'), cls.attr('name')); - ret += ''; - ret += ''; - ret += ''; - } - ret += '
          ' + a + '' + cldoc.Doc.either(cls) + '
          '; - } - return ret; +\tvar a, classes, cls, j, len, ret; +\tret = '
          '; +\tret += cldoc.Page.make_link(this.ref, this.name, { +\t 'id': this.id +\t}); +\tret += new cldoc.Doc(this.brief).render(); +\tclasses = this.node.children('class,struct'); +\tif (classes.length > 0) { +\t ret += ''; +\t for (j = 0, len = classes.length; j < len; j++) { +\t\tcls = classes[j]; +\t\tcls = $(cls); +\t\tret += ''; +\t\ta = cldoc.Page.make_link(cls.attr('ref'), cls.attr('name')); +\t\tret += ''; +\t\tret += ''; +\t\tret += ''; +\t } +\t ret += '
          ' + a + '' + cldoc.Doc.either(cls) + '
          '; +\t} +\treturn ret; }; return Namespace; @@ -1707,21 +1707,21 @@ cldoc.Typedef = (function(superClass) { Typedef.render_container_tag = 'table'; function Typedef(node1) { - this.node = node1; - Typedef.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tTypedef.__super__.constructor.call(this, this.node); } Typedef.prototype.render = function() { - var e, ret; - e = cldoc.html_escape; - ret = '
          ' + e(this.node.attr('name')) + 'type' + new cldoc.Type(this.node.children('type')).render() + '
          ' + cldoc.Doc.either(this.node) + '
          ' + e(this.node.attr('name')) + 'type' + new cldoc.Type(this.node.children('type')).render() + '
          ' + cldoc.Doc.either(this.node) + '
          ' + e(this.node.attr('name')) + '' + new cldoc.Type(this.node.children('type')).render() + '' + cldoc.Doc.either(this.node) + '
          ' + e(this.node.attr('name')) + '' + new cldoc.Type(this.node.children('type')).render() + '' + cldoc.Doc.either(this.node) + '
          '; - retu = this.node.children('return'); - returntype = null; - if (retu.length > 0) { - returntype = new cldoc.Type(retu.children('type')); - } - e = cldoc.html_escape; - for (i = j = 0, ref2 = args.length - 1; j <= ref2; i = j += 1) { - arg = $(args[i]); - argtype = new cldoc.Type(arg.children('type')); - ret += ''; - ret += ''; - ret += ''; - } - if (returntype && returntype.node.attr('name') !== 'void') { - ret += ''; - ret += ''; - ret += ''; - } - ret += '
          ' + e(arg.attr('name')) + '' + cldoc.Doc.either(arg); - if (argtype.allow_none) { - ret += '(may be NULL)'; - } - ret += '
          return' + cldoc.Doc.either(retu); - if (returntype.transfer_ownership === 'full') { - ret += '(owned by caller)'; - } else if (returntype.transfer_ownership === 'container') { - ret += '(container owned by caller)'; - } - ret += '
          '; - return ret; +\tvar arg, args, argtype, e, i, j, ref2, ret, retu, returntype; +\targs = this.node.children('argument'); +\tret = ''; +\tretu = this.node.children('return'); +\treturntype = null; +\tif (retu.length > 0) { +\t returntype = new cldoc.Type(retu.children('type')); +\t} +\te = cldoc.html_escape; +\tfor (i = j = 0, ref2 = args.length - 1; j <= ref2; i = j += 1) { +\t arg = $(args[i]); +\t argtype = new cldoc.Type(arg.children('type')); +\t ret += ''; +\t ret += ''; +\t ret += ''; +\t} +\tif (returntype && returntype.node.attr('name') !== 'void') { +\t ret += ''; +\t ret += ''; +\t ret += ''; +\t} +\tret += '
          ' + e(arg.attr('name')) + '' + cldoc.Doc.either(arg); +\t if (argtype.allow_none) { +\t\tret += '(may be NULL)'; +\t } +\t ret += '
          return' + cldoc.Doc.either(retu); +\t if (returntype.transfer_ownership === 'full') { +\t\tret += '(owned by caller)'; +\t } else if (returntype.transfer_ownership === 'container') { +\t\tret += '(container owned by caller)'; +\t } +\t ret += '
          '; +\treturn ret; }; Function.prototype.render = function() { - var arg, args, argtype, e, i, isover, isprot, isstat, isvirt, j, name, o, ov, override, ref2, ref3, ret, retu, returntype; - e = cldoc.html_escape; - ret = '
          '; - ret += '
          '; - isvirt = this.node.attr('virtual'); - isprot = this.node.attr('access') === 'protected'; - isstat = this.node.attr('static'); - if (isvirt || isprot || isstat) { - ret += '
            '; - if (isstat) { - ret += '
          • static
          • '; - } - if (isprot) { - ret += '
          • protected
          • '; - } - if (isvirt) { - isover = this.node.attr('override'); - if (isover) { - ret += '
          • override
          • '; - } else { - ret += '
          • virtual
          • '; - } - if (this.node.attr('abstract')) { - ret += '
          • abstract
          • '; - } - } - ret += '
          '; - } - retu = this.node.children('return'); - returntype = null; - if (retu.length > 0) { - returntype = new cldoc.Type(retu.children('type')); - ret += '
          ' + returntype.render() + '
          '; - } - ret += ''; - ret += ''; - ret += ''; - args = this.node.children('argument'); - for (i = j = 0, ref2 = args.length - 1; j <= ref2; i = j += 1) { - if (i !== 0) { - ret += ''; - } - arg = $(args[i]); - argtype = new cldoc.Type(arg.children('type')); - ret += ''; - name = arg.attr('name'); - if (i !== args.length - 1) { - name += ','; - } - ret += ''; - } - if (args.length === 0) { - ret += ''; - } - ret += '
          ' + e(this.identifier_for_display()) + '(
          ' + argtype.render() + '' + e(name) + ')
          '; - ret += cldoc.Doc.either(this.node); - ret += this.render_arguments(); - override = this.node.children('override'); - if (override.length > 0) { - ret += '
          Overrides: '; - for (i = o = 0, ref3 = override.length - 1; 0 <= ref3 ? o <= ref3 : o >= ref3; i = 0 <= ref3 ? ++o : --o) { - ov = $(override[i]); - if (i !== 0) { - if (i === override.length - 1) { - ret += ' and '; - } else { - ret += ', '; - } - } - ret += cldoc.Page.make_link(ov.attr('ref'), ov.attr('name')); - } - ret += '
          '; - } - return ret + '
          '; +\tvar arg, args, argtype, e, i, isover, isprot, isstat, isvirt, j, name, o, ov, override, ref2, ref3, ret, retu, returntype; +\te = cldoc.html_escape; +\tret = '
          '; +\tret += '
          '; +\tisvirt = this.node.attr('virtual'); +\tisprot = this.node.attr('access') === 'protected'; +\tisstat = this.node.attr('static'); +\tif (isvirt || isprot || isstat) { +\t ret += '
            '; +\t if (isstat) { +\t\tret += '
          • static
          • '; +\t } +\t if (isprot) { +\t\tret += '
          • protected
          • '; +\t } +\t if (isvirt) { +\t\tisover = this.node.attr('override'); +\t\tif (isover) { +\t\t ret += '
          • override
          • '; +\t\t} else { +\t\t ret += '
          • virtual
          • '; +\t\t} +\t\tif (this.node.attr('abstract')) { +\t\t ret += '
          • abstract
          • '; +\t\t} +\t } +\t ret += '
          '; +\t} +\tretu = this.node.children('return'); +\treturntype = null; +\tif (retu.length > 0) { +\t returntype = new cldoc.Type(retu.children('type')); +\t ret += '
          ' + returntype.render() + '
          '; +\t} +\tret += ''; +\tret += ''; +\tret += ''; +\targs = this.node.children('argument'); +\tfor (i = j = 0, ref2 = args.length - 1; j <= ref2; i = j += 1) { +\t if (i !== 0) { +\t\tret += ''; +\t } +\t arg = $(args[i]); +\t argtype = new cldoc.Type(arg.children('type')); +\t ret += ''; +\t name = arg.attr('name'); +\t if (i !== args.length - 1) { +\t\tname += ','; +\t } +\t ret += ''; +\t} +\tif (args.length === 0) { +\t ret += ''; +\t} +\tret += '
          ' + e(this.identifier_for_display()) + '(
          ' + argtype.render() + '' + e(name) + ')
          '; +\tret += cldoc.Doc.either(this.node); +\tret += this.render_arguments(); +\toverride = this.node.children('override'); +\tif (override.length > 0) { +\t ret += '
          Overrides: '; +\t for (i = o = 0, ref3 = override.length - 1; 0 <= ref3 ? o <= ref3 : o >= ref3; i = 0 <= ref3 ? ++o : --o) { +\t\tov = $(override[i]); +\t\tif (i !== 0) { +\t\t if (i === override.length - 1) { +\t\t\tret += ' and '; +\t\t } else { +\t\t\tret += ', '; +\t\t } +\t\t} +\t\tret += cldoc.Page.make_link(ov.attr('ref'), ov.attr('name')); +\t } +\t ret += '
          '; +\t} +\treturn ret + '
          '; }; return Function; @@ -1895,7 +1895,7 @@ cldoc.FunctionTemplate = (function(superClass) { extend(FunctionTemplate, superClass); function FunctionTemplate() { - return FunctionTemplate.__super__.constructor.apply(this, arguments); +\treturn FunctionTemplate.__super__.constructor.apply(this, arguments); } return FunctionTemplate; @@ -1912,18 +1912,18 @@ cldoc.Field = (function(superClass) { Field.render_container_tag = 'table'; function Field(node1) { - this.node = node1; - Field.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tField.__super__.constructor.call(this, this.node); } Field.prototype.render = function() { - var e, ret; - e = cldoc.html_escape; - ret = ''; - ret += '' + e(this.node.attr('name')) + ''; - ret += '' + new cldoc.Type(this.node.children('type')).render() + ''; - ret += '' + cldoc.Doc.either(this.node) + ''; - return ret + ''; +\tvar e, ret; +\te = cldoc.html_escape; +\tret = ''; +\tret += '' + e(this.node.attr('name')) + ''; +\tret += '' + new cldoc.Type(this.node.children('type')).render() + ''; +\tret += '' + cldoc.Doc.either(this.node) + ''; +\treturn ret + ''; }; return Field; @@ -1938,8 +1938,8 @@ cldoc.Method = (function(superClass) { Method.title = ['Member Function', 'Member Functions']; function Method(node1) { - this.node = node1; - Method.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tMethod.__super__.constructor.call(this, this.node); } return Method; @@ -1952,7 +1952,7 @@ cldoc.MethodTemplate = (function(superClass) { extend(MethodTemplate, superClass); function MethodTemplate() { - return MethodTemplate.__super__.constructor.apply(this, arguments); +\treturn MethodTemplate.__super__.constructor.apply(this, arguments); } return MethodTemplate; @@ -1967,8 +1967,8 @@ cldoc.Constructor = (function(superClass) { Constructor.title = ['Constructor', 'Constructors']; function Constructor(node1) { - this.node = node1; - Constructor.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tConstructor.__super__.constructor.call(this, this.node); } return Constructor; @@ -1983,8 +1983,8 @@ cldoc.Destructor = (function(superClass) { Destructor.title = ['Destructor', 'Destructors']; function Destructor(node1) { - this.node = node1; - Destructor.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tDestructor.__super__.constructor.call(this, this.node); } return Destructor; @@ -2001,31 +2001,31 @@ cldoc.Base = (function(superClass) { Base.render_container_tag = 'table'; function Base(node1) { - var ref; - this.node = node1; - Base.__super__.constructor.call(this, this.node); - this.type = this.node.children('type'); - this.access = this.node.attr('access'); - this.name = this.type.attr('name'); - ref = this.type.attr('ref'); - if (ref) { - this.id = ref.replace('#', '+'); - } +\tvar ref; +\tthis.node = node1; +\tBase.__super__.constructor.call(this, this.node); +\tthis.type = this.node.children('type'); +\tthis.access = this.node.attr('access'); +\tthis.name = this.type.attr('name'); +\tref = this.type.attr('ref'); +\tif (ref) { +\t this.id = ref.replace('#', '+'); +\t} } Base.prototype.render = function() { - var access, e, ret, type; - e = cldoc.html_escape; - ret = ''; - access = this.access; - if (access === 'public') { - access = ''; - } - type = new cldoc.Type(this.type); - ret += '' + e(access) + ''; - ret += '' + type.render() + ''; - ret += '' + cldoc.Doc.brief(this.node) + ''; - return ret + ''; +\tvar access, e, ret, type; +\te = cldoc.html_escape; +\tret = ''; +\taccess = this.access; +\tif (access === 'public') { +\t access = ''; +\t} +\ttype = new cldoc.Type(this.type); +\tret += '' + e(access) + ''; +\tret += '' + type.render() + ''; +\tret += '' + cldoc.Doc.brief(this.node) + ''; +\treturn ret + ''; }; return Base; @@ -2042,31 +2042,31 @@ cldoc.Implements = (function(superClass) { Implements.render_container_tag = 'table'; function Implements(node1) { - var ref; - this.node = node1; - Implements.__super__.constructor.call(this, this.node); - this.type = this.node.children('type'); - this.access = this.node.attr('access'); - this.name = this.type.attr('name'); - ref = this.type.attr('ref'); - if (ref) { - this.id = ref.replace('#', '+'); - } +\tvar ref; +\tthis.node = node1; +\tImplements.__super__.constructor.call(this, this.node); +\tthis.type = this.node.children('type'); +\tthis.access = this.node.attr('access'); +\tthis.name = this.type.attr('name'); +\tref = this.type.attr('ref'); +\tif (ref) { +\t this.id = ref.replace('#', '+'); +\t} } Implements.prototype.render = function() { - var access, e, ret, type; - e = cldoc.html_escape; - ret = ''; - access = this.access; - if (access === 'public') { - access = ''; - } - type = new cldoc.Type(this.type); - ret += '' + e(access) + ''; - ret += '' + type.render() + ''; - ret += '' + cldoc.Doc.brief(this.node) + ''; - return ret + ''; +\tvar access, e, ret, type; +\te = cldoc.html_escape; +\tret = ''; +\taccess = this.access; +\tif (access === 'public') { +\t access = ''; +\t} +\ttype = new cldoc.Type(this.type); +\tret += '' + e(access) + ''; +\tret += '' + type.render() + ''; +\tret += '' + cldoc.Doc.brief(this.node) + ''; +\treturn ret + ''; }; return Implements; @@ -2083,24 +2083,24 @@ cldoc.Subclass = (function(superClass) { Subclass.render_container_tag = 'table'; function Subclass(node1) { - this.node = node1; - Subclass.__super__.constructor.call(this, this.node); - this.access = this.node.attr('access'); +\tthis.node = node1; +\tSubclass.__super__.constructor.call(this, this.node); +\tthis.access = this.node.attr('access'); } Subclass.prototype.render = function() { - var access, e, ret; - e = cldoc.html_escape; - ret = ''; - access = this.access; - if (access === 'public') { - access = ''; - } - ret += '' + e(access) + ''; - ret += '' + cldoc.Page.make_link(this.ref, this.name) + ''; - ret += '' + cldoc.Doc.brief(this.node) + ''; - ret += ''; - return ret; +\tvar access, e, ret; +\te = cldoc.html_escape; +\tret = ''; +\taccess = this.access; +\tif (access === 'public') { +\t access = ''; +\t} +\tret += '' + e(access) + ''; +\tret += '' + cldoc.Page.make_link(this.ref, this.name) + ''; +\tret += '' + cldoc.Doc.brief(this.node) + ''; +\tret += ''; +\treturn ret; }; return Subclass; @@ -2117,23 +2117,23 @@ cldoc.ImplementedBy = (function(superClass) { ImplementedBy.render_container_tag = 'table'; function ImplementedBy(node1) { - this.node = node1; - ImplementedBy.__super__.constructor.call(this, this.node); - this.access = this.node.attr('access'); +\tthis.node = node1; +\tImplementedBy.__super__.constructor.call(this, this.node); +\tthis.access = this.node.attr('access'); } ImplementedBy.prototype.render = function() { - var access, e, ret; - e = cldoc.html_escape; - ret = ''; - access = this.access; - if (access === 'public') { - access = ''; - } - ret += '' + e(access) + ''; - ret += '' + cldoc.Page.make_link(this.ref, this.name) + ''; - ret += '' + cldoc.Doc.brief(this.node) + ''; - return ret + ''; +\tvar access, e, ret; +\te = cldoc.html_escape; +\tret = ''; +\taccess = this.access; +\tif (access === 'public') { +\t access = ''; +\t} +\tret += '' + e(access) + ''; +\tret += '' + cldoc.Page.make_link(this.ref, this.name) + ''; +\tret += '' + cldoc.Doc.brief(this.node) + ''; +\treturn ret + ''; }; return ImplementedBy; @@ -2146,7 +2146,7 @@ cldoc.TemplateTypeParameter = (function(superClass) { extend(TemplateTypeParameter, superClass); function TemplateTypeParameter() { - return TemplateTypeParameter.__super__.constructor.apply(this, arguments); +\treturn TemplateTypeParameter.__super__.constructor.apply(this, arguments); } TemplateTypeParameter.title = ['Template Parameter', 'Template Parameters']; @@ -2154,24 +2154,24 @@ cldoc.TemplateTypeParameter = (function(superClass) { TemplateTypeParameter.render_container_tag = 'table'; TemplateTypeParameter.prototype.render = function() { - var def, e, name, ret, tp; - e = cldoc.html_escape; - name = this.name; - def = this.node.attr('default'); - tp = this.node.children('type'); - ret = ''; - name = ''; - if (tp.length > 0) { - name += (new cldoc.Type(tp)).render() + ' '; - } - name += e(this.name); - if (def) { - name += ' = ' + def + ''; - } - ret += '' + name + ''; - ret += '' + cldoc.Doc.brief(this.node) + ''; - ret += ''; - return ret; +\tvar def, e, name, ret, tp; +\te = cldoc.html_escape; +\tname = this.name; +\tdef = this.node.attr('default'); +\ttp = this.node.children('type'); +\tret = ''; +\tname = ''; +\tif (tp.length > 0) { +\t name += (new cldoc.Type(tp)).render() + ' '; +\t} +\tname += e(this.name); +\tif (def) { +\t name += ' = ' + def + ''; +\t} +\tret += '' + name + ''; +\tret += '' + cldoc.Doc.brief(this.node) + ''; +\tret += ''; +\treturn ret; }; return TemplateTypeParameter; @@ -2188,93 +2188,93 @@ cldoc.Coverage = (function(superClass) { Coverage.title = ['Coverage', 'Coverage']; function Coverage(node1) { - this.node = node1; - Coverage.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tCoverage.__super__.constructor.call(this, this.node); } Coverage.prototype.get_coverage = function(type) { - var ret; - ret = { - documented: parseInt(type.attr('documented')), - undocumented: parseInt(type.attr('undocumented')) - }; - ret.total = ret.documented + ret.undocumented; - ret.percentage = Math.round(100 * ret.documented / ret.total); - return ret; +\tvar ret; +\tret = { +\t documented: parseInt(type.attr('documented')), +\t undocumented: parseInt(type.attr('undocumented')) +\t}; +\tret.total = ret.documented + ret.undocumented; +\tret.percentage = Math.round(100 * ret.documented / ret.total); +\treturn ret; }; Coverage.prototype.render_sidebar_type = function(type) { - var a, cov, e, ret, tt, typename; - typename = type.attr('name'); - cov = this.get_coverage(type); - e = cldoc.html_escape; - if (cov.documented === 0 && cov.undocumented === 0) { - return; - } - tt = cov.documented + ' out of ' + cov.total + ' (' + cov.percentage + '%)'; - a = cldoc.Page.make_link(cldoc.Page.current_page + '#' + typename, typename); - ret = '
        1. '; - if (cov.undocumented === 0) { - ret += ''; - } else { - ret += ''; - } - ret += a + '
          ' + e(tt) + '
          '; - return ret + '
        2. '; +\tvar a, cov, e, ret, tt, typename; +\ttypename = type.attr('name'); +\tcov = this.get_coverage(type); +\te = cldoc.html_escape; +\tif (cov.documented === 0 && cov.undocumented === 0) { +\t return; +\t} +\ttt = cov.documented + ' out of ' + cov.total + ' (' + cov.percentage + '%)'; +\ta = cldoc.Page.make_link(cldoc.Page.current_page + '#' + typename, typename); +\tret = '
        3. '; +\tif (cov.undocumented === 0) { +\t ret += ''; +\t} else { +\t ret += ''; +\t} +\tret += a + '
          ' + e(tt) + '
          '; +\treturn ret + '
        4. '; }; Coverage.prototype.render_sidebar = function() { - var j, len, ret, type, types; - types = this.node.children('type'); - ret = ''; - for (j = 0, len = types.length; j < len; j++) { - type = types[j]; - ret += this.render_sidebar_type($(type)); - } - return ret; +\tvar j, len, ret, type, types; +\ttypes = this.node.children('type'); +\tret = ''; +\tfor (j = 0, len = types.length; j < len; j++) { +\t type = types[j]; +\t ret += this.render_sidebar_type($(type)); +\t} +\treturn ret; }; Coverage.prototype.render_type = function(type) { - var cov, e, file, j, len, len1, line, loc, o, ref2, ref3, ret, typename, undoc; - ret = ''; - typename = type.attr('name'); - cov = this.get_coverage(type); - if (cov.documented === 0 && cov.undocumented === 0) { - return ret; - } - e = cldoc.html_escape; - ret += '

          ' + e(typename + ' (' + cov.percentage + '%)') + '

          '; - ret += ''; - ret += ''; - ret += ''; - ret += '
          Documented:' + e(cov.documented) + '
          Undocumented:' + e(cov.undocumented) + '
          '; - ref2 = type.children('undocumented'); - for (j = 0, len = ref2.length; j < len; j++) { - undoc = ref2[j]; - undoc = $(undoc); - ret += ''; - ref3 = undoc.children('location'); - for (o = 0, len1 = ref3.length; o < len1; o++) { - loc = ref3[o]; - loc = $(loc); - file = e(loc.attr('file')); - line = e(loc.attr('line') + ':' + loc.attr('column')); - ret += ''; - ret += ''; - } - } - return ret + '
          ' + e(undoc.attr('id')) + '' + file + '' + line + '
          '; +\tvar cov, e, file, j, len, len1, line, loc, o, ref2, ref3, ret, typename, undoc; +\tret = ''; +\ttypename = type.attr('name'); +\tcov = this.get_coverage(type); +\tif (cov.documented === 0 && cov.undocumented === 0) { +\t return ret; +\t} +\te = cldoc.html_escape; +\tret += '

          ' + e(typename + ' (' + cov.percentage + '%)') + '

          '; +\tret += ''; +\tret += ''; +\tret += ''; +\tret += '
          Documented:' + e(cov.documented) + '
          Undocumented:' + e(cov.undocumented) + '
          '; +\tref2 = type.children('undocumented'); +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t undoc = ref2[j]; +\t undoc = $(undoc); +\t ret += ''; +\t ref3 = undoc.children('location'); +\t for (o = 0, len1 = ref3.length; o < len1; o++) { +\t\tloc = ref3[o]; +\t\tloc = $(loc); +\t\tfile = e(loc.attr('file')); +\t\tline = e(loc.attr('line') + ':' + loc.attr('column')); +\t\tret += ''; +\t\tret += ''; +\t } +\t} +\treturn ret + '
          ' + e(undoc.attr('id')) + '' + file + '' + line + '
          '; }; Coverage.prototype.render = function() { - var j, len, ret, type, types; - types = this.node.children('type'); - ret = ''; - for (j = 0, len = types.length; j < len; j++) { - type = types[j]; - ret += this.render_type($(type)); - } - return ret; +\tvar j, len, ret, type, types; +\ttypes = this.node.children('type'); +\tret = ''; +\tfor (j = 0, len = types.length; j < len; j++) { +\t type = types[j]; +\t ret += this.render_type($(type)); +\t} +\treturn ret; }; return Coverage; @@ -2289,82 +2289,82 @@ cldoc.Arguments = (function(superClass) { Arguments.title = ['Arguments', 'Arguments']; function Arguments(node1) { - this.node = node1; - Arguments.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tArguments.__super__.constructor.call(this, this.node); } Arguments.prototype.render_sidebar_function = function(func) { - var a; - a = cldoc.Page.make_link(cldoc.Page.current_page + '#' + func.attr('id'), func.attr('name')); - return '
        5. ' + a + '
        6. '; +\tvar a; +\ta = cldoc.Page.make_link(cldoc.Page.current_page + '#' + func.attr('id'), func.attr('name')); +\treturn '
        7. ' + a + '
        8. '; }; Arguments.prototype.render_sidebar = function() { - var f, funcs, j, len, ret; - funcs = this.node.children('function'); - ret = ''; - for (j = 0, len = funcs.length; j < len; j++) { - f = funcs[j]; - ret += this.render_sidebar_function($(f)); - } - return ret; +\tvar f, funcs, j, len, ret; +\tfuncs = this.node.children('function'); +\tret = ''; +\tfor (j = 0, len = funcs.length; j < len; j++) { +\t f = funcs[j]; +\t ret += this.render_sidebar_function($(f)); +\t} +\treturn ret; }; Arguments.prototype.render_function = function(func) { - var e, file, j, len, line, loc, misspelled, names, ref2, ret, undocumented, x; - e = cldoc.html_escape; - ret = ' ' + e(func.attr('name')) + ''; - ref2 = func.children('location'); - for (j = 0, len = ref2.length; j < len; j++) { - loc = ref2[j]; - loc = $(loc); - file = e(loc.attr('file')); - line = e(loc.attr('line') + ':' + loc.attr('column')); - ret += '' + file + '' + line + ''; - ret += ''; - } - ret += ''; - undocumented = func.children('undocumented'); - if (undocumented.length > 0) { - names = ((function() { - var len1, o, results1; - results1 = []; - for (o = 0, len1 = undocumented.length; o < len1; o++) { - x = undocumented[o]; - results1.push($(x).attr('name')); - } - return results1; - })()).join(', '); - ret += 'Undocumented arguments:' + '' + e(names) + ''; - } - misspelled = func.children('misspelled'); - if (misspelled.length > 0) { - names = ((function() { - var len1, o, results1; - results1 = []; - for (o = 0, len1 = undocumented.length; o < len1; o++) { - x = undocumented[o]; - results1.push($(x).attr('name')); - } - return results1; - })()).join(', '); - ret += 'Misspelled arguments:' + '' + e(names) + ''; - } - if (func.children('undocumented-return')) { - ret += 'Undocumented return value'; - } - return ret; +\tvar e, file, j, len, line, loc, misspelled, names, ref2, ret, undocumented, x; +\te = cldoc.html_escape; +\tret = ' ' + e(func.attr('name')) + ''; +\tref2 = func.children('location'); +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t loc = ref2[j]; +\t loc = $(loc); +\t file = e(loc.attr('file')); +\t line = e(loc.attr('line') + ':' + loc.attr('column')); +\t ret += '' + file + '' + line + ''; +\t ret += ''; +\t} +\tret += ''; +\tundocumented = func.children('undocumented'); +\tif (undocumented.length > 0) { +\t names = ((function() { +\t\tvar len1, o, results1; +\t\tresults1 = []; +\t\tfor (o = 0, len1 = undocumented.length; o < len1; o++) { +\t\t x = undocumented[o]; +\t\t results1.push($(x).attr('name')); +\t\t} +\t\treturn results1; +\t })()).join(', '); +\t ret += 'Undocumented arguments:' + '' + e(names) + ''; +\t} +\tmisspelled = func.children('misspelled'); +\tif (misspelled.length > 0) { +\t names = ((function() { +\t\tvar len1, o, results1; +\t\tresults1 = []; +\t\tfor (o = 0, len1 = undocumented.length; o < len1; o++) { +\t\t x = undocumented[o]; +\t\t results1.push($(x).attr('name')); +\t\t} +\t\treturn results1; +\t })()).join(', '); +\t ret += 'Misspelled arguments:' + '' + e(names) + ''; +\t} +\tif (func.children('undocumented-return')) { +\t ret += 'Undocumented return value'; +\t} +\treturn ret; }; Arguments.prototype.render = function() { - var c, f, funcs, j, len; - funcs = this.node.children('function'); - c = ''; - for (j = 0, len = funcs.length; j < len; j++) { - f = funcs[j]; - c += this.render_function($(f)); - } - return c + '
          '; +\tvar c, f, funcs, j, len; +\tfuncs = this.node.children('function'); +\tc = ''; +\tfor (j = 0, len = funcs.length; j < len; j++) { +\t f = funcs[j]; +\t c += this.render_function($(f)); +\t} +\treturn c + '
          '; }; return Arguments; @@ -2379,12 +2379,12 @@ cldoc.Report = (function(superClass) { Report.title = ['Report', 'Report']; function Report(node1) { - this.node = node1; - Report.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tReport.__super__.constructor.call(this, this.node); } Report.prototype.render_sidebar = function() { - return '
        9. ' + cldoc.Page.make_link(this.ref, this.name) + '
        10. '; +\treturn '
        11. ' + cldoc.Page.make_link(this.ref, this.name) + '
        12. '; }; Report.prototype.render = function(container) {}; @@ -2403,73 +2403,73 @@ cldoc.References = (function(superClass) { References.render_container_tag = 'table'; function References(node1) { - this.node = node1; - References.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tReferences.__super__.constructor.call(this, this.node); } References.prototype.render_sidebar = function() { - var a, child, e, j, len, ref2, ret; - ret = ''; - e = cldoc.html_escape; - ref2 = this.node.children(); - for (j = 0, len = ref2.length; j < len; j++) { - child = ref2[j]; - child = $(child); - a = cldoc.Page.make_link(cldoc.Page.current_page + '#ref-' + child.attr('id'), child.attr('name')); - ret += '
        13. ' + e(cldoc.tag(child)[0]) + ' ' + a + '
        14. '; - } - return ret; +\tvar a, child, e, j, len, ref2, ret; +\tret = ''; +\te = cldoc.html_escape; +\tref2 = this.node.children(); +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t child = ref2[j]; +\t child = $(child); +\t a = cldoc.Page.make_link(cldoc.Page.current_page + '#ref-' + child.attr('id'), child.attr('name')); +\t ret += '
        15. ' + e(cldoc.tag(child)[0]) + ' ' + a + '
        16. '; +\t} +\treturn ret; }; References.prototype.render = function() { - var child, component, e, file, id, j, kw, len, len1, len2, line, loc, name, o, p, ref2, ref3, ref4, refs, ret, tp, x; - ret = ''; - e = cldoc.html_escape; - ref2 = this.node.children(); - for (j = 0, len = ref2.length; j < len; j++) { - child = ref2[j]; - child = $(child); - kw = '' + e(cldoc.tag(child)[0]) + ' ' + ''; - id = '' + e(child.attr('id')) + ''; - ret += '' + kw + id + ''; - ref3 = child.children('location'); - for (o = 0, len1 = ref3.length; o < len1; o++) { - loc = ref3[o]; - loc = $(loc); - file = e(loc.attr('file')); - line = e(loc.attr('line') + ':' + loc.attr('column')); - ret += '' + file + ''; - ret += '' + line + ''; - ret += ''; - } - ret += ''; - ref4 = child.children('doctype'); - for (p = 0, len2 = ref4.length; p < len2; p++) { - tp = ref4[p]; - tp = $(tp); - name = tp.attr('name'); - component = tp.attr('component'); - if (component) { - name += '.' + component; - } - refs = ((function() { - var len3, ref5, results1, u; - ref5 = tp.children('ref'); - results1 = []; - for (u = 0, len3 = ref5.length; u < len3; u++) { - x = ref5[u]; - results1.push($(x).attr('name')); - } - return results1; - })()).join(', '); - ret += ''; - ret += '' + e(name) + ''; - ret += '' + e(refs) + ''; - ret += ''; - ret += ''; - } - } - return ret; +\tvar child, component, e, file, id, j, kw, len, len1, len2, line, loc, name, o, p, ref2, ref3, ref4, refs, ret, tp, x; +\tret = ''; +\te = cldoc.html_escape; +\tref2 = this.node.children(); +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t child = ref2[j]; +\t child = $(child); +\t kw = '' + e(cldoc.tag(child)[0]) + ' ' + ''; +\t id = '' + e(child.attr('id')) + ''; +\t ret += '' + kw + id + ''; +\t ref3 = child.children('location'); +\t for (o = 0, len1 = ref3.length; o < len1; o++) { +\t\tloc = ref3[o]; +\t\tloc = $(loc); +\t\tfile = e(loc.attr('file')); +\t\tline = e(loc.attr('line') + ':' + loc.attr('column')); +\t\tret += '' + file + ''; +\t\tret += '' + line + ''; +\t\tret += ''; +\t } +\t ret += ''; +\t ref4 = child.children('doctype'); +\t for (p = 0, len2 = ref4.length; p < len2; p++) { +\t\ttp = ref4[p]; +\t\ttp = $(tp); +\t\tname = tp.attr('name'); +\t\tcomponent = tp.attr('component'); +\t\tif (component) { +\t\t name += '.' + component; +\t\t} +\t\trefs = ((function() { +\t\t var len3, ref5, results1, u; +\t\t ref5 = tp.children('ref'); +\t\t results1 = []; +\t\t for (u = 0, len3 = ref5.length; u < len3; u++) { +\t\t\tx = ref5[u]; +\t\t\tresults1.push($(x).attr('name')); +\t\t } +\t\t return results1; +\t\t})()).join(', '); +\t\tret += ''; +\t\tret += '' + e(name) + ''; +\t\tret += '' + e(refs) + ''; +\t\tret += ''; +\t\tret += ''; +\t } +\t} +\treturn ret; }; return References; @@ -2486,27 +2486,27 @@ cldoc.Union = (function(superClass) { Union.render_container_tag = 'table'; function Union(node1) { - this.node = node1; - Union.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tUnion.__super__.constructor.call(this, this.node); } Union.prototype.render = function() { - var child, j, len, ref2, ret, tp; - ret = ''; - ret += 'union'; - ret += ''; - ret += '' + cldoc.Doc.either(this.node) + ''; - ret += ''; - ref2 = this.node.children(); - for (j = 0, len = ref2.length; j < len; j++) { - child = ref2[j]; - child = $(child); - tp = cldoc.Page.node_type(child); - if (tp) { - ret += new tp(child).render(); - } - } - return ret + '
          '; +\tvar child, j, len, ref2, ret, tp; +\tret = ''; +\tret += 'union'; +\tret += ''; +\tret += '' + cldoc.Doc.either(this.node) + ''; +\tret += ''; +\tref2 = this.node.children(); +\tfor (j = 0, len = ref2.length; j < len; j++) { +\t child = ref2[j]; +\t child = $(child); +\t tp = cldoc.Page.node_type(child); +\t if (tp) { +\t\tret += new tp(child).render(); +\t } +\t} +\treturn ret + '
          '; }; return Union; @@ -2521,9 +2521,9 @@ cldoc.GObjectClass = (function(superClass) { GObjectClass.title = ['GObject Class', 'GObject Classes']; function GObjectClass(node1) { - this.node = node1; - GObjectClass.__super__.constructor.call(this, this.node); - this.keyword = 'struct'; +\tthis.node = node1; +\tGObjectClass.__super__.constructor.call(this, this.node); +\tthis.keyword = 'struct'; } return GObjectClass; @@ -2538,9 +2538,9 @@ cldoc.GObjectInterface = (function(superClass) { GObjectInterface.title = ['GObject Interface', 'GObject Interfaces']; function GObjectInterface(node1) { - this.node = node1; - GObjectInterface.__super__.constructor.call(this, this.node); - this.keyword = 'interface'; +\tthis.node = node1; +\tGObjectInterface.__super__.constructor.call(this, this.node); +\tthis.keyword = 'interface'; } return GObjectInterface; @@ -2555,9 +2555,9 @@ cldoc.GObjectBoxed = (function(superClass) { GObjectBoxed.title = ['GObject Boxed Structure', 'GObject Boxed Structures']; function GObjectBoxed(node1) { - this.node = node1; - GObjectBoxed.__super__.constructor.call(this, this.node); - this.keyword = 'struct'; +\tthis.node = node1; +\tGObjectBoxed.__super__.constructor.call(this, this.node); +\tthis.keyword = 'struct'; } return GObjectBoxed; @@ -2574,29 +2574,29 @@ cldoc.GObjectProperty = (function(superClass) { GObjectProperty.render_container_tag = 'table'; function GObjectProperty(node1) { - this.node = node1; - GObjectProperty.__super__.constructor.call(this, this.node); +\tthis.node = node1; +\tGObjectProperty.__super__.constructor.call(this, this.node); } GObjectProperty.prototype.render = function() { - var e, j, len, mode, ref2, ret, x; - e = cldoc.html_escape; - ret = ''; - ret += '' + e(this.node.attr('name')) + ''; - mode = this.node.attr('mode'); - ret += ''; - if (mode) { - ret += '
            '; - ref2 = mode.split(','); - for (j = 0, len = ref2.length; j < len; j++) { - x = ref2[j]; - ret += '
          • ' + e(x) + '
          • '; - } - ret += '
          '; - } - ret += '' + new cldoc.Type(this.node.children('type')).render() + ''; - ret += '' + cldoc.Doc.either(this.node) + ''; - return ret + ''; +\tvar e, j, len, mode, ref2, ret, x; +\te = cldoc.html_escape; +\tret = ''; +\tret += '' + e(this.node.attr('name')) + ''; +\tmode = this.node.attr('mode'); +\tret += ''; +\tif (mode) { +\t ret += '
            '; +\t ref2 = mode.split(','); +\t for (j = 0, len = ref2.length; j < len; j++) { +\t\tx = ref2[j]; +\t\tret += '
          • ' + e(x) + '
          • '; +\t } +\t ret += '
          '; +\t} +\tret += '' + new cldoc.Type(this.node.children('type')).render() + ''; +\tret += '' + cldoc.Doc.either(this.node) + ''; +\treturn ret + ''; }; return GObjectProperty; diff --git a/cldoc/data/javascript/jquery-1.9.1.js b/cldoc/data/javascript/jquery-1.9.1.js index e2c203f..d25ada7 100644 --- a/cldoc/data/javascript/jquery-1.9.1.js +++ b/cldoc/data/javascript/jquery-1.9.1.js @@ -19,950 +19,950 @@ // Support: Firefox 18+ //"use strict"; var - // The deferred used on DOM ready - readyList, - - // A central reference to the root jQuery(document) - rootjQuery, - - // Support: IE<9 - // For `typeof node.method` instead of `node.method !== undefined` - core_strundefined = typeof undefined, - - // Use the correct document accordingly with window argument (sandbox) - document = window.document, - location = window.location, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // [[Class]] -> type pairs - class2type = {}, - - // List of deleted data cache ids, so we can reuse them - core_deletedIds = [], - - core_version = "1.9.1", - - // Save a reference to some core methods - core_concat = core_deletedIds.concat, - core_push = core_deletedIds.push, - core_slice = core_deletedIds.slice, - core_indexOf = core_deletedIds.indexOf, - core_toString = class2type.toString, - core_hasOwn = class2type.hasOwnProperty, - core_trim = core_version.trim, - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Used for matching numbers - core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, - - // Used for splitting on whitespace - core_rnotwhite = /\S+/g, - - // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, - rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, - - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([\da-z])/gi, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }, - - // The ready event handler - completed = function( event ) { - - // readyState === "complete" is good enough for us to call the dom ready in oldIE - if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { - detach(); - jQuery.ready(); - } - }, - // Clean-up method for dom ready events - detach = function() { - if ( document.addEventListener ) { - document.removeEventListener( "DOMContentLoaded", completed, false ); - window.removeEventListener( "load", completed, false ); - - } else { - document.detachEvent( "onreadystatechange", completed ); - window.detachEvent( "onload", completed ); - } - }; +\t// The deferred used on DOM ready +\treadyList, + +\t// A central reference to the root jQuery(document) +\trootjQuery, + +\t// Support: IE<9 +\t// For `typeof node.method` instead of `node.method !== undefined` +\tcore_strundefined = typeof undefined, + +\t// Use the correct document accordingly with window argument (sandbox) +\tdocument = window.document, +\tlocation = window.location, + +\t// Map over jQuery in case of overwrite +\t_jQuery = window.jQuery, + +\t// Map over the $ in case of overwrite +\t_$ = window.$, + +\t// [[Class]] -> type pairs +\tclass2type = {}, + +\t// List of deleted data cache ids, so we can reuse them +\tcore_deletedIds = [], + +\tcore_version = "1.9.1", + +\t// Save a reference to some core methods +\tcore_concat = core_deletedIds.concat, +\tcore_push = core_deletedIds.push, +\tcore_slice = core_deletedIds.slice, +\tcore_indexOf = core_deletedIds.indexOf, +\tcore_toString = class2type.toString, +\tcore_hasOwn = class2type.hasOwnProperty, +\tcore_trim = core_version.trim, + +\t// Define a local copy of jQuery +\tjQuery = function( selector, context ) { +\t\t// The jQuery object is actually just the init constructor 'enhanced' +\t\treturn new jQuery.fn.init( selector, context, rootjQuery ); +\t}, + +\t// Used for matching numbers +\tcore_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, + +\t// Used for splitting on whitespace +\tcore_rnotwhite = /\S+/g, + +\t// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) +\trtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + +\t// A simple way to check for HTML strings +\t// Prioritize #id over to avoid XSS via location.hash (#9521) +\t// Strict HTML recognition (#11290: must start with <) +\trquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, + +\t// Match a standalone tag +\trsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + +\t// JSON RegExp +\trvalidchars = /^[\],:{}\s]*$/, +\trvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, +\trvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, +\trvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, + +\t// Matches dashed string for camelizing +\trmsPrefix = /^-ms-/, +\trdashAlpha = /-([\da-z])/gi, + +\t// Used by jQuery.camelCase as callback to replace() +\tfcamelCase = function( all, letter ) { +\t\treturn letter.toUpperCase(); +\t}, + +\t// The ready event handler +\tcompleted = function( event ) { + +\t\t// readyState === "complete" is good enough for us to call the dom ready in oldIE +\t\tif ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { +\t\t\tdetach(); +\t\t\tjQuery.ready(); +\t\t} +\t}, +\t// Clean-up method for dom ready events +\tdetach = function() { +\t\tif ( document.addEventListener ) { +\t\t\tdocument.removeEventListener( "DOMContentLoaded", completed, false ); +\t\t\twindow.removeEventListener( "load", completed, false ); + +\t\t} else { +\t\t\tdocument.detachEvent( "onreadystatechange", completed ); +\t\t\twindow.detachEvent( "onload", completed ); +\t\t} +\t}; jQuery.fn = jQuery.prototype = { - // The current version of jQuery being used - jquery: core_version, - - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - - // scripts is true for back-compat - jQuery.merge( this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return core_slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - ret.context = this.context; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); - - return this; - }, - - slice: function() { - return this.pushStack( core_slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: core_push, - sort: [].sort, - splice: [].splice +\t// The current version of jQuery being used +\tjquery: core_version, + +\tconstructor: jQuery, +\tinit: function( selector, context, rootjQuery ) { +\t\tvar match, elem; + +\t\t// HANDLE: $(""), $(null), $(undefined), $(false) +\t\tif ( !selector ) { +\t\t\treturn this; +\t\t} + +\t\t// Handle HTML strings +\t\tif ( typeof selector === "string" ) { +\t\t\tif ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { +\t\t\t\t// Assume that strings that start and end with <> are HTML and skip the regex check +\t\t\t\tmatch = [ null, selector, null ]; + +\t\t\t} else { +\t\t\t\tmatch = rquickExpr.exec( selector ); +\t\t\t} + +\t\t\t// Match html or make sure no context is specified for #id +\t\t\tif ( match && (match[1] || !context) ) { + +\t\t\t\t// HANDLE: $(html) -> $(array) +\t\t\t\tif ( match[1] ) { +\t\t\t\t\tcontext = context instanceof jQuery ? context[0] : context; + +\t\t\t\t\t// scripts is true for back-compat +\t\t\t\t\tjQuery.merge( this, jQuery.parseHTML( +\t\t\t\t\t\tmatch[1], +\t\t\t\t\t\tcontext && context.nodeType ? context.ownerDocument || context : document, +\t\t\t\t\t\ttrue +\t\t\t\t\t) ); + +\t\t\t\t\t// HANDLE: $(html, props) +\t\t\t\t\tif ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { +\t\t\t\t\t\tfor ( match in context ) { +\t\t\t\t\t\t\t// Properties of context are called as methods if possible +\t\t\t\t\t\t\tif ( jQuery.isFunction( this[ match ] ) ) { +\t\t\t\t\t\t\t\tthis[ match ]( context[ match ] ); + +\t\t\t\t\t\t\t// ...and otherwise set as attributes +\t\t\t\t\t\t\t} else { +\t\t\t\t\t\t\t\tthis.attr( match, context[ match ] ); +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} +\t\t\t\t\t} + +\t\t\t\t\treturn this; + +\t\t\t\t// HANDLE: $(#id) +\t\t\t\t} else { +\t\t\t\t\telem = document.getElementById( match[2] ); + +\t\t\t\t\t// Check parentNode to catch when Blackberry 4.6 returns +\t\t\t\t\t// nodes that are no longer in the document #6963 +\t\t\t\t\tif ( elem && elem.parentNode ) { +\t\t\t\t\t\t// Handle the case where IE and Opera return items +\t\t\t\t\t\t// by name instead of ID +\t\t\t\t\t\tif ( elem.id !== match[2] ) { +\t\t\t\t\t\t\treturn rootjQuery.find( selector ); +\t\t\t\t\t\t} + +\t\t\t\t\t\t// Otherwise, we inject the element directly into the jQuery object +\t\t\t\t\t\tthis.length = 1; +\t\t\t\t\t\tthis[0] = elem; +\t\t\t\t\t} + +\t\t\t\t\tthis.context = document; +\t\t\t\t\tthis.selector = selector; +\t\t\t\t\treturn this; +\t\t\t\t} + +\t\t\t// HANDLE: $(expr, $(...)) +\t\t\t} else if ( !context || context.jquery ) { +\t\t\t\treturn ( context || rootjQuery ).find( selector ); + +\t\t\t// HANDLE: $(expr, context) +\t\t\t// (which is just equivalent to: $(context).find(expr) +\t\t\t} else { +\t\t\t\treturn this.constructor( context ).find( selector ); +\t\t\t} + +\t\t// HANDLE: $(DOMElement) +\t\t} else if ( selector.nodeType ) { +\t\t\tthis.context = this[0] = selector; +\t\t\tthis.length = 1; +\t\t\treturn this; + +\t\t// HANDLE: $(function) +\t\t// Shortcut for document ready +\t\t} else if ( jQuery.isFunction( selector ) ) { +\t\t\treturn rootjQuery.ready( selector ); +\t\t} + +\t\tif ( selector.selector !== undefined ) { +\t\t\tthis.selector = selector.selector; +\t\t\tthis.context = selector.context; +\t\t} + +\t\treturn jQuery.makeArray( selector, this ); +\t}, + +\t// Start with an empty selector +\tselector: "", + +\t// The default length of a jQuery object is 0 +\tlength: 0, + +\t// The number of elements contained in the matched element set +\tsize: function() { +\t\treturn this.length; +\t}, + +\ttoArray: function() { +\t\treturn core_slice.call( this ); +\t}, + +\t// Get the Nth element in the matched element set OR +\t// Get the whole matched element set as a clean array +\tget: function( num ) { +\t\treturn num == null ? + +\t\t\t// Return a 'clean' array +\t\t\tthis.toArray() : + +\t\t\t// Return just the object +\t\t\t( num < 0 ? this[ this.length + num ] : this[ num ] ); +\t}, + +\t// Take an array of elements and push it onto the stack +\t// (returning the new matched element set) +\tpushStack: function( elems ) { + +\t\t// Build a new jQuery matched element set +\t\tvar ret = jQuery.merge( this.constructor(), elems ); + +\t\t// Add the old object onto the stack (as a reference) +\t\tret.prevObject = this; +\t\tret.context = this.context; + +\t\t// Return the newly-formed element set +\t\treturn ret; +\t}, + +\t// Execute a callback for every element in the matched set. +\t// (You can seed the arguments with an array of args, but this is +\t// only used internally.) +\teach: function( callback, args ) { +\t\treturn jQuery.each( this, callback, args ); +\t}, + +\tready: function( fn ) { +\t\t// Add the callback +\t\tjQuery.ready.promise().done( fn ); + +\t\treturn this; +\t}, + +\tslice: function() { +\t\treturn this.pushStack( core_slice.apply( this, arguments ) ); +\t}, + +\tfirst: function() { +\t\treturn this.eq( 0 ); +\t}, + +\tlast: function() { +\t\treturn this.eq( -1 ); +\t}, + +\teq: function( i ) { +\t\tvar len = this.length, +\t\t\tj = +i + ( i < 0 ? len : 0 ); +\t\treturn this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); +\t}, + +\tmap: function( callback ) { +\t\treturn this.pushStack( jQuery.map(this, function( elem, i ) { +\t\t\treturn callback.call( elem, i, elem ); +\t\t})); +\t}, + +\tend: function() { +\t\treturn this.prevObject || this.constructor(null); +\t}, + +\t// For internal use only. +\t// Behaves like an Array's method, not like a jQuery method. +\tpush: core_push, +\tsort: [].sort, +\tsplice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { - var src, copyIsArray, copy, name, options, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; +\tvar src, copyIsArray, copy, name, options, clone, +\t\ttarget = arguments[0] || {}, +\t\ti = 1, +\t\tlength = arguments.length, +\t\tdeep = false; + +\t// Handle a deep copy situation +\tif ( typeof target === "boolean" ) { +\t\tdeep = target; +\t\ttarget = arguments[1] || {}; +\t\t// skip the boolean and the target +\t\ti = 2; +\t} + +\t// Handle case when target is a string or something (possible in deep copy) +\tif ( typeof target !== "object" && !jQuery.isFunction(target) ) { +\t\ttarget = {}; +\t} + +\t// extend jQuery itself if only one argument is passed +\tif ( length === i ) { +\t\ttarget = this; +\t\t--i; +\t} + +\tfor ( ; i < length; i++ ) { +\t\t// Only deal with non-null/undefined values +\t\tif ( (options = arguments[ i ]) != null ) { +\t\t\t// Extend the base object +\t\t\tfor ( name in options ) { +\t\t\t\tsrc = target[ name ]; +\t\t\t\tcopy = options[ name ]; + +\t\t\t\t// Prevent never-ending loop +\t\t\t\tif ( target === copy ) { +\t\t\t\t\tcontinue; +\t\t\t\t} + +\t\t\t\t// Recurse if we're merging plain objects or arrays +\t\t\t\tif ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { +\t\t\t\t\tif ( copyIsArray ) { +\t\t\t\t\t\tcopyIsArray = false; +\t\t\t\t\t\tclone = src && jQuery.isArray(src) ? src : []; + +\t\t\t\t\t} else { +\t\t\t\t\t\tclone = src && jQuery.isPlainObject(src) ? src : {}; +\t\t\t\t\t} + +\t\t\t\t\t// Never move original objects, clone them +\t\t\t\t\ttarget[ name ] = jQuery.extend( deep, clone, copy ); + +\t\t\t\t// Don't bring in undefined values +\t\t\t\t} else if ( copy !== undefined ) { +\t\t\t\t\ttarget[ name ] = copy; +\t\t\t\t} +\t\t\t} +\t\t} +\t} + +\t// Return the modified object +\treturn target; }; jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger("ready").off("ready"); - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - isWindow: function( obj ) { - return obj != null && obj == obj.window; - }, - - isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - - type: function( obj ) { - if ( obj == null ) { - return String( obj ); - } - return typeof obj === "object" || typeof obj === "function" ? - class2type[ core_toString.call(obj) ] || "object" : - typeof obj; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - try { - // Not own constructor property must be Object - if ( obj.constructor && - !core_hasOwn.call(obj, "constructor") && - !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || core_hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - var name; - for ( name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw new Error( msg ); - }, - - // data: string of html - // context (optional): If specified, the fragment will be created in this context, defaults to document - // keepScripts (optional): If true, will include scripts passed in the html string - parseHTML: function( data, context, keepScripts ) { - if ( !data || typeof data !== "string" ) { - return null; - } - if ( typeof context === "boolean" ) { - keepScripts = context; - context = false; - } - context = context || document; - - var parsed = rsingleTag.exec( data ), - scripts = !keepScripts && []; - - // Single tag - if ( parsed ) { - return [ context.createElement( parsed[1] ) ]; - } - - parsed = jQuery.buildFragment( [ data ], context, scripts ); - if ( scripts ) { - jQuery( scripts ).remove(); - } - return jQuery.merge( [], parsed.childNodes ); - }, - - parseJSON: function( data ) { - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - if ( data === null ) { - return data; - } - - if ( typeof data === "string" ) { - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - if ( data ) { - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return ( new Function( "return " + data ) )(); - } - } - } - - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - parseXML: function( data ) { - var xml, tmp; - if ( !data || typeof data !== "string" ) { - return null; - } - try { - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - } catch( e ) { - xml = undefined; - } - if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && jQuery.trim( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - }, - - // args is for internal usage only - each: function( obj, callback, args ) { - var value, - i = 0, - length = obj.length, - isArray = isArraylike( obj ); - - if ( args ) { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } - } - - return obj; - }, - - // Use native String.trim function wherever possible - trim: core_trim && !core_trim.call("\uFEFF\xA0") ? - function( text ) { - return text == null ? - "" : - core_trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - ( text + "" ).replace( rtrim, "" ); - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArraylike( Object(arr) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - core_push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - var len; - - if ( arr ) { - if ( core_indexOf ) { - return core_indexOf.call( arr, elem, i ); - } - - len = arr.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in arr && arr[ i ] === elem ) { - return i; - } - } - } - - return -1; - }, - - merge: function( first, second ) { - var l = second.length, - i = first.length, - j = 0; - - if ( typeof l === "number" ) { - for ( ; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var retVal, - ret = [], - i = 0, - length = elems.length; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, - i = 0, - length = elems.length, - isArray = isArraylike( elems ), - ret = []; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return core_concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var args, proxy, tmp; - - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - args = core_slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }, - - // Multifunctional method to get and set values of a collection - // The value/s can optionally be executed if it's a function - access: function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - length = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < length; i++ ) { - fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - length ? fn( elems[0], key ) : emptyGet; - }, - - now: function() { - return ( new Date() ).getTime(); - } +\tnoConflict: function( deep ) { +\t\tif ( window.$ === jQuery ) { +\t\t\twindow.$ = _$; +\t\t} + +\t\tif ( deep && window.jQuery === jQuery ) { +\t\t\twindow.jQuery = _jQuery; +\t\t} + +\t\treturn jQuery; +\t}, + +\t// Is the DOM ready to be used? Set to true once it occurs. +\tisReady: false, + +\t// A counter to track how many items to wait for before +\t// the ready event fires. See #6781 +\treadyWait: 1, + +\t// Hold (or release) the ready event +\tholdReady: function( hold ) { +\t\tif ( hold ) { +\t\t\tjQuery.readyWait++; +\t\t} else { +\t\t\tjQuery.ready( true ); +\t\t} +\t}, + +\t// Handle when the DOM is ready +\tready: function( wait ) { + +\t\t// Abort if there are pending holds or we're already ready +\t\tif ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { +\t\t\treturn; +\t\t} + +\t\t// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). +\t\tif ( !document.body ) { +\t\t\treturn setTimeout( jQuery.ready ); +\t\t} + +\t\t// Remember that the DOM is ready +\t\tjQuery.isReady = true; + +\t\t// If a normal DOM Ready event fired, decrement, and wait if need be +\t\tif ( wait !== true && --jQuery.readyWait > 0 ) { +\t\t\treturn; +\t\t} + +\t\t// If there are functions bound, to execute +\t\treadyList.resolveWith( document, [ jQuery ] ); + +\t\t// Trigger any bound ready events +\t\tif ( jQuery.fn.trigger ) { +\t\t\tjQuery( document ).trigger("ready").off("ready"); +\t\t} +\t}, + +\t// See test/unit/core.js for details concerning isFunction. +\t// Since version 1.3, DOM methods and functions like alert +\t// aren't supported. They return false on IE (#2968). +\tisFunction: function( obj ) { +\t\treturn jQuery.type(obj) === "function"; +\t}, + +\tisArray: Array.isArray || function( obj ) { +\t\treturn jQuery.type(obj) === "array"; +\t}, + +\tisWindow: function( obj ) { +\t\treturn obj != null && obj == obj.window; +\t}, + +\tisNumeric: function( obj ) { +\t\treturn !isNaN( parseFloat(obj) ) && isFinite( obj ); +\t}, + +\ttype: function( obj ) { +\t\tif ( obj == null ) { +\t\t\treturn String( obj ); +\t\t} +\t\treturn typeof obj === "object" || typeof obj === "function" ? +\t\t\tclass2type[ core_toString.call(obj) ] || "object" : +\t\t\ttypeof obj; +\t}, + +\tisPlainObject: function( obj ) { +\t\t// Must be an Object. +\t\t// Because of IE, we also have to check the presence of the constructor property. +\t\t// Make sure that DOM nodes and window objects don't pass through, as well +\t\tif ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { +\t\t\treturn false; +\t\t} + +\t\ttry { +\t\t\t// Not own constructor property must be Object +\t\t\tif ( obj.constructor && +\t\t\t\t!core_hasOwn.call(obj, "constructor") && +\t\t\t\t!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { +\t\t\t\treturn false; +\t\t\t} +\t\t} catch ( e ) { +\t\t\t// IE8,9 Will throw exceptions on certain host objects #9897 +\t\t\treturn false; +\t\t} + +\t\t// Own properties are enumerated firstly, so to speed up, +\t\t// if last one is own, then all properties are own. + +\t\tvar key; +\t\tfor ( key in obj ) {} + +\t\treturn key === undefined || core_hasOwn.call( obj, key ); +\t}, + +\tisEmptyObject: function( obj ) { +\t\tvar name; +\t\tfor ( name in obj ) { +\t\t\treturn false; +\t\t} +\t\treturn true; +\t}, + +\terror: function( msg ) { +\t\tthrow new Error( msg ); +\t}, + +\t// data: string of html +\t// context (optional): If specified, the fragment will be created in this context, defaults to document +\t// keepScripts (optional): If true, will include scripts passed in the html string +\tparseHTML: function( data, context, keepScripts ) { +\t\tif ( !data || typeof data !== "string" ) { +\t\t\treturn null; +\t\t} +\t\tif ( typeof context === "boolean" ) { +\t\t\tkeepScripts = context; +\t\t\tcontext = false; +\t\t} +\t\tcontext = context || document; + +\t\tvar parsed = rsingleTag.exec( data ), +\t\t\tscripts = !keepScripts && []; + +\t\t// Single tag +\t\tif ( parsed ) { +\t\t\treturn [ context.createElement( parsed[1] ) ]; +\t\t} + +\t\tparsed = jQuery.buildFragment( [ data ], context, scripts ); +\t\tif ( scripts ) { +\t\t\tjQuery( scripts ).remove(); +\t\t} +\t\treturn jQuery.merge( [], parsed.childNodes ); +\t}, + +\tparseJSON: function( data ) { +\t\t// Attempt to parse using the native JSON parser first +\t\tif ( window.JSON && window.JSON.parse ) { +\t\t\treturn window.JSON.parse( data ); +\t\t} + +\t\tif ( data === null ) { +\t\t\treturn data; +\t\t} + +\t\tif ( typeof data === "string" ) { + +\t\t\t// Make sure leading/trailing whitespace is removed (IE can't handle it) +\t\t\tdata = jQuery.trim( data ); + +\t\t\tif ( data ) { +\t\t\t\t// Make sure the incoming data is actual JSON +\t\t\t\t// Logic borrowed from http://json.org/json2.js +\t\t\t\tif ( rvalidchars.test( data.replace( rvalidescape, "@" ) +\t\t\t\t\t.replace( rvalidtokens, "]" ) +\t\t\t\t\t.replace( rvalidbraces, "")) ) { + +\t\t\t\t\treturn ( new Function( "return " + data ) )(); +\t\t\t\t} +\t\t\t} +\t\t} + +\t\tjQuery.error( "Invalid JSON: " + data ); +\t}, + +\t// Cross-browser xml parsing +\tparseXML: function( data ) { +\t\tvar xml, tmp; +\t\tif ( !data || typeof data !== "string" ) { +\t\t\treturn null; +\t\t} +\t\ttry { +\t\t\tif ( window.DOMParser ) { // Standard +\t\t\t\ttmp = new DOMParser(); +\t\t\t\txml = tmp.parseFromString( data , "text/xml" ); +\t\t\t} else { // IE +\t\t\t\txml = new ActiveXObject( "Microsoft.XMLDOM" ); +\t\t\t\txml.async = "false"; +\t\t\t\txml.loadXML( data ); +\t\t\t} +\t\t} catch( e ) { +\t\t\txml = undefined; +\t\t} +\t\tif ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { +\t\t\tjQuery.error( "Invalid XML: " + data ); +\t\t} +\t\treturn xml; +\t}, + +\tnoop: function() {}, + +\t// Evaluates a script in a global context +\t// Workarounds based on findings by Jim Driscoll +\t// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context +\tglobalEval: function( data ) { +\t\tif ( data && jQuery.trim( data ) ) { +\t\t\t// We use execScript on Internet Explorer +\t\t\t// We use an anonymous function so that context is window +\t\t\t// rather than jQuery in Firefox +\t\t\t( window.execScript || function( data ) { +\t\t\t\twindow[ "eval" ].call( window, data ); +\t\t\t} )( data ); +\t\t} +\t}, + +\t// Convert dashed to camelCase; used by the css and data modules +\t// Microsoft forgot to hump their vendor prefix (#9572) +\tcamelCase: function( string ) { +\t\treturn string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +\t}, + +\tnodeName: function( elem, name ) { +\t\treturn elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); +\t}, + +\t// args is for internal usage only +\teach: function( obj, callback, args ) { +\t\tvar value, +\t\t\ti = 0, +\t\t\tlength = obj.length, +\t\t\tisArray = isArraylike( obj ); + +\t\tif ( args ) { +\t\t\tif ( isArray ) { +\t\t\t\tfor ( ; i < length; i++ ) { +\t\t\t\t\tvalue = callback.apply( obj[ i ], args ); + +\t\t\t\t\tif ( value === false ) { +\t\t\t\t\t\tbreak; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} else { +\t\t\t\tfor ( i in obj ) { +\t\t\t\t\tvalue = callback.apply( obj[ i ], args ); + +\t\t\t\t\tif ( value === false ) { +\t\t\t\t\t\tbreak; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} + +\t\t// A special, fast, case for the most common use of each +\t\t} else { +\t\t\tif ( isArray ) { +\t\t\t\tfor ( ; i < length; i++ ) { +\t\t\t\t\tvalue = callback.call( obj[ i ], i, obj[ i ] ); + +\t\t\t\t\tif ( value === false ) { +\t\t\t\t\t\tbreak; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} else { +\t\t\t\tfor ( i in obj ) { +\t\t\t\t\tvalue = callback.call( obj[ i ], i, obj[ i ] ); + +\t\t\t\t\tif ( value === false ) { +\t\t\t\t\t\tbreak; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} + +\t\treturn obj; +\t}, + +\t// Use native String.trim function wherever possible +\ttrim: core_trim && !core_trim.call("\uFEFF\xA0") ? +\t\tfunction( text ) { +\t\t\treturn text == null ? +\t\t\t\t"" : +\t\t\t\tcore_trim.call( text ); +\t\t} : + +\t\t// Otherwise use our own trimming functionality +\t\tfunction( text ) { +\t\t\treturn text == null ? +\t\t\t\t"" : +\t\t\t\t( text + "" ).replace( rtrim, "" ); +\t\t}, + +\t// results is for internal usage only +\tmakeArray: function( arr, results ) { +\t\tvar ret = results || []; + +\t\tif ( arr != null ) { +\t\t\tif ( isArraylike( Object(arr) ) ) { +\t\t\t\tjQuery.merge( ret, +\t\t\t\t\ttypeof arr === "string" ? +\t\t\t\t\t[ arr ] : arr +\t\t\t\t); +\t\t\t} else { +\t\t\t\tcore_push.call( ret, arr ); +\t\t\t} +\t\t} + +\t\treturn ret; +\t}, + +\tinArray: function( elem, arr, i ) { +\t\tvar len; + +\t\tif ( arr ) { +\t\t\tif ( core_indexOf ) { +\t\t\t\treturn core_indexOf.call( arr, elem, i ); +\t\t\t} + +\t\t\tlen = arr.length; +\t\t\ti = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + +\t\t\tfor ( ; i < len; i++ ) { +\t\t\t\t// Skip accessing in sparse arrays +\t\t\t\tif ( i in arr && arr[ i ] === elem ) { +\t\t\t\t\treturn i; +\t\t\t\t} +\t\t\t} +\t\t} + +\t\treturn -1; +\t}, + +\tmerge: function( first, second ) { +\t\tvar l = second.length, +\t\t\ti = first.length, +\t\t\tj = 0; + +\t\tif ( typeof l === "number" ) { +\t\t\tfor ( ; j < l; j++ ) { +\t\t\t\tfirst[ i++ ] = second[ j ]; +\t\t\t} +\t\t} else { +\t\t\twhile ( second[j] !== undefined ) { +\t\t\t\tfirst[ i++ ] = second[ j++ ]; +\t\t\t} +\t\t} + +\t\tfirst.length = i; + +\t\treturn first; +\t}, + +\tgrep: function( elems, callback, inv ) { +\t\tvar retVal, +\t\t\tret = [], +\t\t\ti = 0, +\t\t\tlength = elems.length; +\t\tinv = !!inv; + +\t\t// Go through the array, only saving the items +\t\t// that pass the validator function +\t\tfor ( ; i < length; i++ ) { +\t\t\tretVal = !!callback( elems[ i ], i ); +\t\t\tif ( inv !== retVal ) { +\t\t\t\tret.push( elems[ i ] ); +\t\t\t} +\t\t} + +\t\treturn ret; +\t}, + +\t// arg is for internal usage only +\tmap: function( elems, callback, arg ) { +\t\tvar value, +\t\t\ti = 0, +\t\t\tlength = elems.length, +\t\t\tisArray = isArraylike( elems ), +\t\t\tret = []; + +\t\t// Go through the array, translating each of the items to their +\t\tif ( isArray ) { +\t\t\tfor ( ; i < length; i++ ) { +\t\t\t\tvalue = callback( elems[ i ], i, arg ); + +\t\t\t\tif ( value != null ) { +\t\t\t\t\tret[ ret.length ] = value; +\t\t\t\t} +\t\t\t} + +\t\t// Go through every key on the object, +\t\t} else { +\t\t\tfor ( i in elems ) { +\t\t\t\tvalue = callback( elems[ i ], i, arg ); + +\t\t\t\tif ( value != null ) { +\t\t\t\t\tret[ ret.length ] = value; +\t\t\t\t} +\t\t\t} +\t\t} + +\t\t// Flatten any nested arrays +\t\treturn core_concat.apply( [], ret ); +\t}, + +\t// A global GUID counter for objects +\tguid: 1, + +\t// Bind a function to a context, optionally partially applying any +\t// arguments. +\tproxy: function( fn, context ) { +\t\tvar args, proxy, tmp; + +\t\tif ( typeof context === "string" ) { +\t\t\ttmp = fn[ context ]; +\t\t\tcontext = fn; +\t\t\tfn = tmp; +\t\t} + +\t\t// Quick check to determine if target is callable, in the spec +\t\t// this throws a TypeError, but we will just return undefined. +\t\tif ( !jQuery.isFunction( fn ) ) { +\t\t\treturn undefined; +\t\t} + +\t\t// Simulated bind +\t\targs = core_slice.call( arguments, 2 ); +\t\tproxy = function() { +\t\t\treturn fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); +\t\t}; + +\t\t// Set the guid of unique handler to the same of original handler, so it can be removed +\t\tproxy.guid = fn.guid = fn.guid || jQuery.guid++; + +\t\treturn proxy; +\t}, + +\t// Multifunctional method to get and set values of a collection +\t// The value/s can optionally be executed if it's a function +\taccess: function( elems, fn, key, value, chainable, emptyGet, raw ) { +\t\tvar i = 0, +\t\t\tlength = elems.length, +\t\t\tbulk = key == null; + +\t\t// Sets many values +\t\tif ( jQuery.type( key ) === "object" ) { +\t\t\tchainable = true; +\t\t\tfor ( i in key ) { +\t\t\t\tjQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); +\t\t\t} + +\t\t// Sets one value +\t\t} else if ( value !== undefined ) { +\t\t\tchainable = true; + +\t\t\tif ( !jQuery.isFunction( value ) ) { +\t\t\t\traw = true; +\t\t\t} + +\t\t\tif ( bulk ) { +\t\t\t\t// Bulk operations run against the entire set +\t\t\t\tif ( raw ) { +\t\t\t\t\tfn.call( elems, value ); +\t\t\t\t\tfn = null; + +\t\t\t\t// ...except when executing function values +\t\t\t\t} else { +\t\t\t\t\tbulk = fn; +\t\t\t\t\tfn = function( elem, key, value ) { +\t\t\t\t\t\treturn bulk.call( jQuery( elem ), value ); +\t\t\t\t\t}; +\t\t\t\t} +\t\t\t} + +\t\t\tif ( fn ) { +\t\t\t\tfor ( ; i < length; i++ ) { +\t\t\t\t\tfn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); +\t\t\t\t} +\t\t\t} +\t\t} + +\t\treturn chainable ? +\t\t\telems : + +\t\t\t// Gets +\t\t\tbulk ? +\t\t\t\tfn.call( elems ) : +\t\t\t\tlength ? fn( elems[0], key ) : emptyGet; +\t}, + +\tnow: function() { +\t\treturn ( new Date() ).getTime(); +\t} }); jQuery.ready.promise = function( obj ) { - if ( !readyList ) { - - readyList = jQuery.Deferred(); - - // Catch cases where $(document).ready() is called after the browser event has already occurred. - // we once tried to use readyState "interactive" here, but it caused issues like the one - // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - setTimeout( jQuery.ready ); - - // Standards-based browsers support DOMContentLoaded - } else if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed, false ); - - // If IE event model is used - } else { - // Ensure firing before onload, maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", completed ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", completed ); - - // If IE and not a frame - // continually check to see if the document is ready - var top = false; - - try { - top = window.frameElement == null && document.documentElement; - } catch(e) {} - - if ( top && top.doScroll ) { - (function doScrollCheck() { - if ( !jQuery.isReady ) { - - try { - // Use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - top.doScroll("left"); - } catch(e) { - return setTimeout( doScrollCheck, 50 ); - } - - // detach all dom ready events - detach(); - - // and execute any waiting functions - jQuery.ready(); - } - })(); - } - } - } - return readyList.promise( obj ); +\tif ( !readyList ) { + +\t\treadyList = jQuery.Deferred(); + +\t\t// Catch cases where $(document).ready() is called after the browser event has already occurred. +\t\t// we once tried to use readyState "interactive" here, but it caused issues like the one +\t\t// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 +\t\tif ( document.readyState === "complete" ) { +\t\t\t// Handle it asynchronously to allow scripts the opportunity to delay ready +\t\t\tsetTimeout( jQuery.ready ); + +\t\t// Standards-based browsers support DOMContentLoaded +\t\t} else if ( document.addEventListener ) { +\t\t\t// Use the handy event callback +\t\t\tdocument.addEventListener( "DOMContentLoaded", completed, false ); + +\t\t\t// A fallback to window.onload, that will always work +\t\t\twindow.addEventListener( "load", completed, false ); + +\t\t// If IE event model is used +\t\t} else { +\t\t\t// Ensure firing before onload, maybe late but safe also for iframes +\t\t\tdocument.attachEvent( "onreadystatechange", completed ); + +\t\t\t// A fallback to window.onload, that will always work +\t\t\twindow.attachEvent( "onload", completed ); + +\t\t\t// If IE and not a frame +\t\t\t// continually check to see if the document is ready +\t\t\tvar top = false; + +\t\t\ttry { +\t\t\t\ttop = window.frameElement == null && document.documentElement; +\t\t\t} catch(e) {} + +\t\t\tif ( top && top.doScroll ) { +\t\t\t\t(function doScrollCheck() { +\t\t\t\t\tif ( !jQuery.isReady ) { + +\t\t\t\t\t\ttry { +\t\t\t\t\t\t\t// Use the trick by Diego Perini +\t\t\t\t\t\t\t// http://javascript.nwbox.com/IEContentLoaded/ +\t\t\t\t\t\t\ttop.doScroll("left"); +\t\t\t\t\t\t} catch(e) { +\t\t\t\t\t\t\treturn setTimeout( doScrollCheck, 50 ); +\t\t\t\t\t\t} + +\t\t\t\t\t\t// detach all dom ready events +\t\t\t\t\t\tdetach(); + +\t\t\t\t\t\t// and execute any waiting functions +\t\t\t\t\t\tjQuery.ready(); +\t\t\t\t\t} +\t\t\t\t})(); +\t\t\t} +\t\t} +\t} +\treturn readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); +\tclass2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { - var length = obj.length, - type = jQuery.type( obj ); +\tvar length = obj.length, +\t\ttype = jQuery.type( obj ); - if ( jQuery.isWindow( obj ) ) { - return false; - } +\tif ( jQuery.isWindow( obj ) ) { +\t\treturn false; +\t} - if ( obj.nodeType === 1 && length ) { - return true; - } +\tif ( obj.nodeType === 1 && length ) { +\t\treturn true; +\t} - return type === "array" || type !== "function" && - ( length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj ); +\treturn type === "array" || type !== "function" && +\t\t( length === 0 || +\t\ttypeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these @@ -972,1739 +972,1739 @@ var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { - var object = optionsCache[ options ] = {}; - jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - }); - return object; +\tvar object = optionsCache[ options ] = {}; +\tjQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { +\t\tobject[ flag ] = true; +\t}); +\treturn object; } /* * Create a callback list using the following parameters: * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object + *\toptions: an optional list of space-separated options that will change how + *\t\t\tthe callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * - * once: will ensure the callback list can only be fired once (like a Deferred) + *\tonce:\t\t\twill ensure the callback list can only be fired once (like a Deferred) * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) + *\tmemory:\t\t\twill keep track of previous values and will call any callback added + *\t\t\t\t\tafter the list has been fired right away with the latest "memorized" + *\t\t\t\t\tvalues (like a Deferred) * - * unique: will ensure a callback can only be added once (no duplicate in the list) + *\tunique:\t\t\twill ensure a callback can only be added once (no duplicate in the list) * - * stopOnFalse: interrupt callings when a callback returns false + *\tstopOnFalse:\tinterrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - ( optionsCache[ options ] || createOptions( options ) ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // First callback to fire (used internally by add and fireWith) - firingStart, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function( data ) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if ( list ) { - if ( stack ) { - if ( stack.length ) { - fire( stack.shift() ); - } - } else if ( memory ) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - // First, we save the current length - var start = list.length; - (function add( args ) { - jQuery.each( args, function( _, arg ) { - var type = jQuery.type( arg ); - if ( type === "function" ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && type !== "string" ) { - // Inspect recursively - add( arg ); - } - }); - })( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if ( memory ) { - firingStart = start; - fire( memory ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - jQuery.each( arguments, function( _, arg ) { - var index; - while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - // Handle firing indexes - if ( firing ) { - if ( index <= firingLength ) { - firingLength--; - } - if ( index <= firingIndex ) { - firingIndex--; - } - } - } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); - }, - // Remove all callbacks from the list - empty: function() { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - if ( list && ( !fired || stack ) ) { - if ( firing ) { - stack.push( args ); - } else { - fire( args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; +\t// Convert options from String-formatted to Object-formatted if needed +\t// (we check in cache first) +\toptions = typeof options === "string" ? +\t\t( optionsCache[ options ] || createOptions( options ) ) : +\t\tjQuery.extend( {}, options ); + +\tvar // Flag to know if list is currently firing +\t\tfiring, +\t\t// Last fire value (for non-forgettable lists) +\t\tmemory, +\t\t// Flag to know if list was already fired +\t\tfired, +\t\t// End of the loop when firing +\t\tfiringLength, +\t\t// Index of currently firing callback (modified by remove if needed) +\t\tfiringIndex, +\t\t// First callback to fire (used internally by add and fireWith) +\t\tfiringStart, +\t\t// Actual callback list +\t\tlist = [], +\t\t// Stack of fire calls for repeatable lists +\t\tstack = !options.once && [], +\t\t// Fire callbacks +\t\tfire = function( data ) { +\t\t\tmemory = options.memory && data; +\t\t\tfired = true; +\t\t\tfiringIndex = firingStart || 0; +\t\t\tfiringStart = 0; +\t\t\tfiringLength = list.length; +\t\t\tfiring = true; +\t\t\tfor ( ; list && firingIndex < firingLength; firingIndex++ ) { +\t\t\t\tif ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { +\t\t\t\t\tmemory = false; // To prevent further calls using add +\t\t\t\t\tbreak; +\t\t\t\t} +\t\t\t} +\t\t\tfiring = false; +\t\t\tif ( list ) { +\t\t\t\tif ( stack ) { +\t\t\t\t\tif ( stack.length ) { +\t\t\t\t\t\tfire( stack.shift() ); +\t\t\t\t\t} +\t\t\t\t} else if ( memory ) { +\t\t\t\t\tlist = []; +\t\t\t\t} else { +\t\t\t\t\tself.disable(); +\t\t\t\t} +\t\t\t} +\t\t}, +\t\t// Actual Callbacks object +\t\tself = { +\t\t\t// Add a callback or a collection of callbacks to the list +\t\t\tadd: function() { +\t\t\t\tif ( list ) { +\t\t\t\t\t// First, we save the current length +\t\t\t\t\tvar start = list.length; +\t\t\t\t\t(function add( args ) { +\t\t\t\t\t\tjQuery.each( args, function( _, arg ) { +\t\t\t\t\t\t\tvar type = jQuery.type( arg ); +\t\t\t\t\t\t\tif ( type === "function" ) { +\t\t\t\t\t\t\t\tif ( !options.unique || !self.has( arg ) ) { +\t\t\t\t\t\t\t\t\tlist.push( arg ); +\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t} else if ( arg && arg.length && type !== "string" ) { +\t\t\t\t\t\t\t\t// Inspect recursively +\t\t\t\t\t\t\t\tadd( arg ); +\t\t\t\t\t\t\t} +\t\t\t\t\t\t}); +\t\t\t\t\t})( arguments ); +\t\t\t\t\t// Do we need to add the callbacks to the +\t\t\t\t\t// current firing batch? +\t\t\t\t\tif ( firing ) { +\t\t\t\t\t\tfiringLength = list.length; +\t\t\t\t\t// With memory, if we're not firing then +\t\t\t\t\t// we should call right away +\t\t\t\t\t} else if ( memory ) { +\t\t\t\t\t\tfiringStart = start; +\t\t\t\t\t\tfire( memory ); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t\treturn this; +\t\t\t}, +\t\t\t// Remove a callback from the list +\t\t\tremove: function() { +\t\t\t\tif ( list ) { +\t\t\t\t\tjQuery.each( arguments, function( _, arg ) { +\t\t\t\t\t\tvar index; +\t\t\t\t\t\twhile( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { +\t\t\t\t\t\t\tlist.splice( index, 1 ); +\t\t\t\t\t\t\t// Handle firing indexes +\t\t\t\t\t\t\tif ( firing ) { +\t\t\t\t\t\t\t\tif ( index <= firingLength ) { +\t\t\t\t\t\t\t\t\tfiringLength--; +\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t\tif ( index <= firingIndex ) { +\t\t\t\t\t\t\t\t\tfiringIndex--; +\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} +\t\t\t\t\t}); +\t\t\t\t} +\t\t\t\treturn this; +\t\t\t}, +\t\t\t// Check if a given callback is in the list. +\t\t\t// If no argument is given, return whether or not list has callbacks attached. +\t\t\thas: function( fn ) { +\t\t\t\treturn fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); +\t\t\t}, +\t\t\t// Remove all callbacks from the list +\t\t\tempty: function() { +\t\t\t\tlist = []; +\t\t\t\treturn this; +\t\t\t}, +\t\t\t// Have the list do nothing anymore +\t\t\tdisable: function() { +\t\t\t\tlist = stack = memory = undefined; +\t\t\t\treturn this; +\t\t\t}, +\t\t\t// Is it disabled? +\t\t\tdisabled: function() { +\t\t\t\treturn !list; +\t\t\t}, +\t\t\t// Lock the list in its current state +\t\t\tlock: function() { +\t\t\t\tstack = undefined; +\t\t\t\tif ( !memory ) { +\t\t\t\t\tself.disable(); +\t\t\t\t} +\t\t\t\treturn this; +\t\t\t}, +\t\t\t// Is it locked? +\t\t\tlocked: function() { +\t\t\t\treturn !stack; +\t\t\t}, +\t\t\t// Call all callbacks with the given context and arguments +\t\t\tfireWith: function( context, args ) { +\t\t\t\targs = args || []; +\t\t\t\targs = [ context, args.slice ? args.slice() : args ]; +\t\t\t\tif ( list && ( !fired || stack ) ) { +\t\t\t\t\tif ( firing ) { +\t\t\t\t\t\tstack.push( args ); +\t\t\t\t\t} else { +\t\t\t\t\t\tfire( args ); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t\treturn this; +\t\t\t}, +\t\t\t// Call all the callbacks with the given arguments +\t\t\tfire: function() { +\t\t\t\tself.fireWith( this, arguments ); +\t\t\t\treturn this; +\t\t\t}, +\t\t\t// To know if the callbacks have already been called at least once +\t\t\tfired: function() { +\t\t\t\treturn !!fired; +\t\t\t} +\t\t}; + +\treturn self; }; jQuery.extend({ - Deferred: function( func ) { - var tuples = [ - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], - [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], - [ "notify", "progress", jQuery.Callbacks("memory") ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred(function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var action = tuple[ 0 ], - fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[1] ](function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .done( newDefer.resolve ) - .fail( newDefer.reject ) - .progress( newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); - } - }); - }); - fns = null; - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Keep pipe for back-compat - promise.pipe = promise.then; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; - - // promise[ done | fail | progress ] = list.add - promise[ tuple[1] ] = list.add; - - // Handle state - if ( stateString ) { - list.add(function() { - // state = [ resolved | rejected ] - state = stateString; - - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } - - // deferred[ resolve | reject | notify ] - deferred[ tuple[0] ] = function() { - deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[0] + "With" ] = list.fireWith; - }); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = core_slice.call( arguments ), - length = resolveValues.length, - - // the count of uncompleted subordinates - remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, - - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), - - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; - if( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); - } - }; - }, - - progressValues, progressContexts, resolveContexts; - - // add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ) - .progress( updateFunc( i, progressContexts, progressValues ) ); - } else { - --remaining; - } - } - } - - // if we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); - } - - return deferred.promise(); - } +\tDeferred: function( func ) { +\t\tvar tuples = [ +\t\t\t\t// action, add listener, listener list, final state +\t\t\t\t[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], +\t\t\t\t[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], +\t\t\t\t[ "notify", "progress", jQuery.Callbacks("memory") ] +\t\t\t], +\t\t\tstate = "pending", +\t\t\tpromise = { +\t\t\t\tstate: function() { +\t\t\t\t\treturn state; +\t\t\t\t}, +\t\t\t\talways: function() { +\t\t\t\t\tdeferred.done( arguments ).fail( arguments ); +\t\t\t\t\treturn this; +\t\t\t\t}, +\t\t\t\tthen: function( /* fnDone, fnFail, fnProgress */ ) { +\t\t\t\t\tvar fns = arguments; +\t\t\t\t\treturn jQuery.Deferred(function( newDefer ) { +\t\t\t\t\t\tjQuery.each( tuples, function( i, tuple ) { +\t\t\t\t\t\t\tvar action = tuple[ 0 ], +\t\t\t\t\t\t\t\tfn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; +\t\t\t\t\t\t\t// deferred[ done | fail | progress ] for forwarding actions to newDefer +\t\t\t\t\t\t\tdeferred[ tuple[1] ](function() { +\t\t\t\t\t\t\t\tvar returned = fn && fn.apply( this, arguments ); +\t\t\t\t\t\t\t\tif ( returned && jQuery.isFunction( returned.promise ) ) { +\t\t\t\t\t\t\t\t\treturned.promise() +\t\t\t\t\t\t\t\t\t\t.done( newDefer.resolve ) +\t\t\t\t\t\t\t\t\t\t.fail( newDefer.reject ) +\t\t\t\t\t\t\t\t\t\t.progress( newDefer.notify ); +\t\t\t\t\t\t\t\t} else { +\t\t\t\t\t\t\t\t\tnewDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); +\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t}); +\t\t\t\t\t\t}); +\t\t\t\t\t\tfns = null; +\t\t\t\t\t}).promise(); +\t\t\t\t}, +\t\t\t\t// Get a promise for this deferred +\t\t\t\t// If obj is provided, the promise aspect is added to the object +\t\t\t\tpromise: function( obj ) { +\t\t\t\t\treturn obj != null ? jQuery.extend( obj, promise ) : promise; +\t\t\t\t} +\t\t\t}, +\t\t\tdeferred = {}; + +\t\t// Keep pipe for back-compat +\t\tpromise.pipe = promise.then; + +\t\t// Add list-specific methods +\t\tjQuery.each( tuples, function( i, tuple ) { +\t\t\tvar list = tuple[ 2 ], +\t\t\t\tstateString = tuple[ 3 ]; + +\t\t\t// promise[ done | fail | progress ] = list.add +\t\t\tpromise[ tuple[1] ] = list.add; + +\t\t\t// Handle state +\t\t\tif ( stateString ) { +\t\t\t\tlist.add(function() { +\t\t\t\t\t// state = [ resolved | rejected ] +\t\t\t\t\tstate = stateString; + +\t\t\t\t// [ reject_list | resolve_list ].disable; progress_list.lock +\t\t\t\t}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); +\t\t\t} + +\t\t\t// deferred[ resolve | reject | notify ] +\t\t\tdeferred[ tuple[0] ] = function() { +\t\t\t\tdeferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); +\t\t\t\treturn this; +\t\t\t}; +\t\t\tdeferred[ tuple[0] + "With" ] = list.fireWith; +\t\t}); + +\t\t// Make the deferred a promise +\t\tpromise.promise( deferred ); + +\t\t// Call given func if any +\t\tif ( func ) { +\t\t\tfunc.call( deferred, deferred ); +\t\t} + +\t\t// All done! +\t\treturn deferred; +\t}, + +\t// Deferred helper +\twhen: function( subordinate /* , ..., subordinateN */ ) { +\t\tvar i = 0, +\t\t\tresolveValues = core_slice.call( arguments ), +\t\t\tlength = resolveValues.length, + +\t\t\t// the count of uncompleted subordinates +\t\t\tremaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + +\t\t\t// the master Deferred. If resolveValues consist of only a single Deferred, just use that. +\t\t\tdeferred = remaining === 1 ? subordinate : jQuery.Deferred(), + +\t\t\t// Update function for both resolve and progress values +\t\t\tupdateFunc = function( i, contexts, values ) { +\t\t\t\treturn function( value ) { +\t\t\t\t\tcontexts[ i ] = this; +\t\t\t\t\tvalues[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; +\t\t\t\t\tif( values === progressValues ) { +\t\t\t\t\t\tdeferred.notifyWith( contexts, values ); +\t\t\t\t\t} else if ( !( --remaining ) ) { +\t\t\t\t\t\tdeferred.resolveWith( contexts, values ); +\t\t\t\t\t} +\t\t\t\t}; +\t\t\t}, + +\t\t\tprogressValues, progressContexts, resolveContexts; + +\t\t// add listeners to Deferred subordinates; treat others as resolved +\t\tif ( length > 1 ) { +\t\t\tprogressValues = new Array( length ); +\t\t\tprogressContexts = new Array( length ); +\t\t\tresolveContexts = new Array( length ); +\t\t\tfor ( ; i < length; i++ ) { +\t\t\t\tif ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { +\t\t\t\t\tresolveValues[ i ].promise() +\t\t\t\t\t\t.done( updateFunc( i, resolveContexts, resolveValues ) ) +\t\t\t\t\t\t.fail( deferred.reject ) +\t\t\t\t\t\t.progress( updateFunc( i, progressContexts, progressValues ) ); +\t\t\t\t} else { +\t\t\t\t\t--remaining; +\t\t\t\t} +\t\t\t} +\t\t} + +\t\t// if we're not waiting on anything, resolve the master +\t\tif ( !remaining ) { +\t\t\tdeferred.resolveWith( resolveContexts, resolveValues ); +\t\t} + +\t\treturn deferred.promise(); +\t} }); jQuery.support = (function() { - var support, all, a, - input, select, fragment, - opt, eventName, isSupported, i, - div = document.createElement("div"); - - // Setup - div.setAttribute( "className", "t" ); - div.innerHTML = "
          a"; - - // Support tests won't run in some limited or non-browser environments - all = div.getElementsByTagName("*"); - a = div.getElementsByTagName("a")[ 0 ]; - if ( !all || !a || !all.length ) { - return {}; - } - - // First batch of tests - select = document.createElement("select"); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName("input")[ 0 ]; - - a.style.cssText = "top:1px;float:left;opacity:.5"; - support = { - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: div.firstChild.nodeType === 3, - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: a.getAttribute("href") === "/a", - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.5/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) - checkOn: !!input.value, - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Tests for enctype support on a form (#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", - - // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode - boxModel: document.compatMode === "CSS1Compat", - - // Will be defined later - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true, - boxSizingReliable: true, - pixelPosition: false - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Support: IE<9 - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - // Check if we can trust getAttribute("value") - input = document.createElement("input"); - input.setAttribute( "value", "" ); - support.input = input.getAttribute( "value" ) === ""; - - // Check if an input maintains its value after becoming a radio - input.value = "t"; - input.setAttribute( "type", "radio" ); - support.radioValue = input.value === "t"; - - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "checked", "t" ); - input.setAttribute( "name", "t" ); - - fragment = document.createDocumentFragment(); - fragment.appendChild( input ); - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE<9 - // Opera does not clone events (and typeof div.attachEvent === undefined). - // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() - if ( div.attachEvent ) { - div.attachEvent( "onclick", function() { - support.noCloneEvent = false; - }); - - div.cloneNode( true ).click(); - } - - // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) - // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php - for ( i in { submit: true, change: true, focusin: true }) { - div.setAttribute( eventName = "on" + i, "t" ); - - support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; - } - - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, marginDiv, tds, - divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", - body = document.getElementsByTagName("body")[0]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - container = document.createElement("div"); - container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; - - body.appendChild( container ).appendChild( div ); - - // Support: IE8 - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - div.innerHTML = "
          t
          "; - tds = div.getElementsByTagName("td"); - tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Support: IE8 - // Check if empty table cells still have offsetWidth/Height - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - - // Check box-sizing and margin behavior - div.innerHTML = ""; - div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; - support.boxSizing = ( div.offsetWidth === 4 ); - support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); - - // Use window.getComputedStyle because jsdom on node.js will break without it. - if ( window.getComputedStyle ) { - support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; - support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. (#3333) - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - marginDiv = div.appendChild( document.createElement("div") ); - marginDiv.style.cssText = div.style.cssText = divReset; - marginDiv.style.marginRight = marginDiv.style.width = "0"; - div.style.width = "1px"; - - support.reliableMarginRight = - !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); - } - - if ( typeof div.style.zoom !== core_strundefined ) { - // Support: IE<8 - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - div.innerHTML = ""; - div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); - - // Support: IE6 - // Check if elements with layout shrink-wrap their children - div.style.display = "block"; - div.innerHTML = "
          "; - div.firstChild.style.width = "5px"; - support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - - if ( support.inlineBlockNeedsLayout ) { - // Prevent IE 6 from affecting layout for positioned elements #11048 - // Prevent IE from shrinking the body in IE 7 mode #12869 - // Support: IE<8 - body.style.zoom = 1; - } - } - - body.removeChild( container ); - - // Null elements to avoid leaks in IE - container = div = tds = marginDiv = null; - }); - - // Null elements to avoid leaks in IE - all = select = fragment = opt = a = input = null; - - return support; +\tvar support, all, a, +\t\tinput, select, fragment, +\t\topt, eventName, isSupported, i, +\t\tdiv = document.createElement("div"); + +\t// Setup +\tdiv.setAttribute( "className", "t" ); +\tdiv.innerHTML = "
          a"; + +\t// Support tests won't run in some limited or non-browser environments +\tall = div.getElementsByTagName("*"); +\ta = div.getElementsByTagName("a")[ 0 ]; +\tif ( !all || !a || !all.length ) { +\t\treturn {}; +\t} + +\t// First batch of tests +\tselect = document.createElement("select"); +\topt = select.appendChild( document.createElement("option") ); +\tinput = div.getElementsByTagName("input")[ 0 ]; + +\ta.style.cssText = "top:1px;float:left;opacity:.5"; +\tsupport = { +\t\t// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) +\t\tgetSetAttribute: div.className !== "t", + +\t\t// IE strips leading whitespace when .innerHTML is used +\t\tleadingWhitespace: div.firstChild.nodeType === 3, + +\t\t// Make sure that tbody elements aren't automatically inserted +\t\t// IE will insert them into empty tables +\t\ttbody: !div.getElementsByTagName("tbody").length, + +\t\t// Make sure that link elements get serialized correctly by innerHTML +\t\t// This requires a wrapper element in IE +\t\thtmlSerialize: !!div.getElementsByTagName("link").length, + +\t\t// Get the style information from getAttribute +\t\t// (IE uses .cssText instead) +\t\tstyle: /top/.test( a.getAttribute("style") ), + +\t\t// Make sure that URLs aren't manipulated +\t\t// (IE normalizes it by default) +\t\threfNormalized: a.getAttribute("href") === "/a", + +\t\t// Make sure that element opacity exists +\t\t// (IE uses filter instead) +\t\t// Use a regex to work around a WebKit issue. See #5145 +\t\topacity: /^0.5/.test( a.style.opacity ), + +\t\t// Verify style float existence +\t\t// (IE uses styleFloat instead of cssFloat) +\t\tcssFloat: !!a.style.cssFloat, + +\t\t// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) +\t\tcheckOn: !!input.value, + +\t\t// Make sure that a selected-by-default option has a working selected property. +\t\t// (WebKit defaults to false instead of true, IE too, if it's in an optgroup) +\t\toptSelected: opt.selected, + +\t\t// Tests for enctype support on a form (#6743) +\t\tenctype: !!document.createElement("form").enctype, + +\t\t// Makes sure cloning an html5 element does not cause problems +\t\t// Where outerHTML is undefined, this still works +\t\thtml5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + +\t\t// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode +\t\tboxModel: document.compatMode === "CSS1Compat", + +\t\t// Will be defined later +\t\tdeleteExpando: true, +\t\tnoCloneEvent: true, +\t\tinlineBlockNeedsLayout: false, +\t\tshrinkWrapBlocks: false, +\t\treliableMarginRight: true, +\t\tboxSizingReliable: true, +\t\tpixelPosition: false +\t}; + +\t// Make sure checked status is properly cloned +\tinput.checked = true; +\tsupport.noCloneChecked = input.cloneNode( true ).checked; + +\t// Make sure that the options inside disabled selects aren't marked as disabled +\t// (WebKit marks them as disabled) +\tselect.disabled = true; +\tsupport.optDisabled = !opt.disabled; + +\t// Support: IE<9 +\ttry { +\t\tdelete div.test; +\t} catch( e ) { +\t\tsupport.deleteExpando = false; +\t} + +\t// Check if we can trust getAttribute("value") +\tinput = document.createElement("input"); +\tinput.setAttribute( "value", "" ); +\tsupport.input = input.getAttribute( "value" ) === ""; + +\t// Check if an input maintains its value after becoming a radio +\tinput.value = "t"; +\tinput.setAttribute( "type", "radio" ); +\tsupport.radioValue = input.value === "t"; + +\t// #11217 - WebKit loses check when the name is after the checked attribute +\tinput.setAttribute( "checked", "t" ); +\tinput.setAttribute( "name", "t" ); + +\tfragment = document.createDocumentFragment(); +\tfragment.appendChild( input ); + +\t// Check if a disconnected checkbox will retain its checked +\t// value of true after appended to the DOM (IE6/7) +\tsupport.appendChecked = input.checked; + +\t// WebKit doesn't clone checked state correctly in fragments +\tsupport.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + +\t// Support: IE<9 +\t// Opera does not clone events (and typeof div.attachEvent === undefined). +\t// IE9-10 clones events bound via attachEvent, but they don't trigger with .click() +\tif ( div.attachEvent ) { +\t\tdiv.attachEvent( "onclick", function() { +\t\t\tsupport.noCloneEvent = false; +\t\t}); + +\t\tdiv.cloneNode( true ).click(); +\t} + +\t// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) +\t// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php +\tfor ( i in { submit: true, change: true, focusin: true }) { +\t\tdiv.setAttribute( eventName = "on" + i, "t" ); + +\t\tsupport[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; +\t} + +\tdiv.style.backgroundClip = "content-box"; +\tdiv.cloneNode( true ).style.backgroundClip = ""; +\tsupport.clearCloneStyle = div.style.backgroundClip === "content-box"; + +\t// Run tests that need a body at doc ready +\tjQuery(function() { +\t\tvar container, marginDiv, tds, +\t\t\tdivReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", +\t\t\tbody = document.getElementsByTagName("body")[0]; + +\t\tif ( !body ) { +\t\t\t// Return for frameset docs that don't have a body +\t\t\treturn; +\t\t} + +\t\tcontainer = document.createElement("div"); +\t\tcontainer.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + +\t\tbody.appendChild( container ).appendChild( div ); + +\t\t// Support: IE8 +\t\t// Check if table cells still have offsetWidth/Height when they are set +\t\t// to display:none and there are still other visible table cells in a +\t\t// table row; if so, offsetWidth/Height are not reliable for use when +\t\t// determining if an element has been hidden directly using +\t\t// display:none (it is still safe to use offsets if a parent element is +\t\t// hidden; don safety goggles and see bug #4512 for more information). +\t\tdiv.innerHTML = "
          t
          "; +\t\ttds = div.getElementsByTagName("td"); +\t\ttds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; +\t\tisSupported = ( tds[ 0 ].offsetHeight === 0 ); + +\t\ttds[ 0 ].style.display = ""; +\t\ttds[ 1 ].style.display = "none"; + +\t\t// Support: IE8 +\t\t// Check if empty table cells still have offsetWidth/Height +\t\tsupport.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + +\t\t// Check box-sizing and margin behavior +\t\tdiv.innerHTML = ""; +\t\tdiv.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; +\t\tsupport.boxSizing = ( div.offsetWidth === 4 ); +\t\tsupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + +\t\t// Use window.getComputedStyle because jsdom on node.js will break without it. +\t\tif ( window.getComputedStyle ) { +\t\t\tsupport.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; +\t\t\tsupport.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + +\t\t\t// Check if div with explicit width and no margin-right incorrectly +\t\t\t// gets computed margin-right based on width of container. (#3333) +\t\t\t// Fails in WebKit before Feb 2011 nightlies +\t\t\t// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right +\t\t\tmarginDiv = div.appendChild( document.createElement("div") ); +\t\t\tmarginDiv.style.cssText = div.style.cssText = divReset; +\t\t\tmarginDiv.style.marginRight = marginDiv.style.width = "0"; +\t\t\tdiv.style.width = "1px"; + +\t\t\tsupport.reliableMarginRight = +\t\t\t\t!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); +\t\t} + +\t\tif ( typeof div.style.zoom !== core_strundefined ) { +\t\t\t// Support: IE<8 +\t\t\t// Check if natively block-level elements act like inline-block +\t\t\t// elements when setting their display to 'inline' and giving +\t\t\t// them layout +\t\t\tdiv.innerHTML = ""; +\t\t\tdiv.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; +\t\t\tsupport.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + +\t\t\t// Support: IE6 +\t\t\t// Check if elements with layout shrink-wrap their children +\t\t\tdiv.style.display = "block"; +\t\t\tdiv.innerHTML = "
          "; +\t\t\tdiv.firstChild.style.width = "5px"; +\t\t\tsupport.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + +\t\t\tif ( support.inlineBlockNeedsLayout ) { +\t\t\t\t// Prevent IE 6 from affecting layout for positioned elements #11048 +\t\t\t\t// Prevent IE from shrinking the body in IE 7 mode #12869 +\t\t\t\t// Support: IE<8 +\t\t\t\tbody.style.zoom = 1; +\t\t\t} +\t\t} + +\t\tbody.removeChild( container ); + +\t\t// Null elements to avoid leaks in IE +\t\tcontainer = div = tds = marginDiv = null; +\t}); + +\t// Null elements to avoid leaks in IE +\tall = select = fragment = opt = a = input = null; + +\treturn support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, - rmultiDash = /([A-Z])/g; +\trmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; - } else { - id = internalKey; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); - } - } - - thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; - - // Test for null|undefined property data - if ( ret == null ) { - - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; - } - } else { - ret = thisCache; - } - - return ret; +\tif ( !jQuery.acceptData( elem ) ) { +\t\treturn; +\t} + +\tvar thisCache, ret, +\t\tinternalKey = jQuery.expando, +\t\tgetByName = typeof name === "string", + +\t\t// We have to handle DOM nodes and JS objects differently because IE6-7 +\t\t// can't GC object references properly across the DOM-JS boundary +\t\tisNode = elem.nodeType, + +\t\t// Only DOM nodes need the global jQuery cache; JS object data is +\t\t// attached directly to the object so GC can occur automatically +\t\tcache = isNode ? jQuery.cache : elem, + +\t\t// Only defining an ID for JS objects if its cache already exists allows +\t\t// the code to shortcut on the same path as a DOM node with no cache +\t\tid = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + +\t// Avoid doing any more work than we need to when trying to get data on an +\t// object that has no data at all +\tif ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { +\t\treturn; +\t} + +\tif ( !id ) { +\t\t// Only DOM nodes need a new unique ID for each element since their data +\t\t// ends up in the global cache +\t\tif ( isNode ) { +\t\t\telem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; +\t\t} else { +\t\t\tid = internalKey; +\t\t} +\t} + +\tif ( !cache[ id ] ) { +\t\tcache[ id ] = {}; + +\t\t// Avoids exposing jQuery metadata on plain JS objects when the object +\t\t// is serialized using JSON.stringify +\t\tif ( !isNode ) { +\t\t\tcache[ id ].toJSON = jQuery.noop; +\t\t} +\t} + +\t// An object can be passed to jQuery.data instead of a key/value pair; this gets +\t// shallow copied over onto the existing cache +\tif ( typeof name === "object" || typeof name === "function" ) { +\t\tif ( pvt ) { +\t\t\tcache[ id ] = jQuery.extend( cache[ id ], name ); +\t\t} else { +\t\t\tcache[ id ].data = jQuery.extend( cache[ id ].data, name ); +\t\t} +\t} + +\tthisCache = cache[ id ]; + +\t// jQuery data() is stored in a separate object inside the object's internal data +\t// cache in order to avoid key collisions between internal data and user-defined +\t// data. +\tif ( !pvt ) { +\t\tif ( !thisCache.data ) { +\t\t\tthisCache.data = {}; +\t\t} + +\t\tthisCache = thisCache.data; +\t} + +\tif ( data !== undefined ) { +\t\tthisCache[ jQuery.camelCase( name ) ] = data; +\t} + +\t// Check for both converted-to-camel and non-converted data property names +\t// If a data property was specified +\tif ( getByName ) { + +\t\t// First Try to find as-is property data +\t\tret = thisCache[ name ]; + +\t\t// Test for null|undefined property data +\t\tif ( ret == null ) { + +\t\t\t// Try to find the camelCased property +\t\t\tret = thisCache[ jQuery.camelCase( name ) ]; +\t\t} +\t} else { +\t\tret = thisCache; +\t} + +\treturn ret; } function internalRemoveData( elem, name, pvt ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var i, l, thisCache, - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - - thisCache = pvt ? cache[ id ] : cache[ id ].data; - - if ( thisCache ) { - - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split(" "); - } - } - } else { - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = name.concat( jQuery.map( name, jQuery.camelCase ) ); - } - - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject( cache[ id ] ) ) { - return; - } - } - - // Destroy the cache - if ( isNode ) { - jQuery.cleanData( [ elem ], true ); - - // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) - } else if ( jQuery.support.deleteExpando || cache != cache.window ) { - delete cache[ id ]; - - // When all else fails, null - } else { - cache[ id ] = null; - } +\tif ( !jQuery.acceptData( elem ) ) { +\t\treturn; +\t} + +\tvar i, l, thisCache, +\t\tisNode = elem.nodeType, + +\t\t// See jQuery.data for more information +\t\tcache = isNode ? jQuery.cache : elem, +\t\tid = isNode ? elem[ jQuery.expando ] : jQuery.expando; + +\t// If there is already no cache entry for this object, there is no +\t// purpose in continuing +\tif ( !cache[ id ] ) { +\t\treturn; +\t} + +\tif ( name ) { + +\t\tthisCache = pvt ? cache[ id ] : cache[ id ].data; + +\t\tif ( thisCache ) { + +\t\t\t// Support array or space separated string names for data keys +\t\t\tif ( !jQuery.isArray( name ) ) { + +\t\t\t\t// try the string as a key before any manipulation +\t\t\t\tif ( name in thisCache ) { +\t\t\t\t\tname = [ name ]; +\t\t\t\t} else { + +\t\t\t\t\t// split the camel cased version by spaces unless a key with the spaces exists +\t\t\t\t\tname = jQuery.camelCase( name ); +\t\t\t\t\tif ( name in thisCache ) { +\t\t\t\t\t\tname = [ name ]; +\t\t\t\t\t} else { +\t\t\t\t\t\tname = name.split(" "); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} else { +\t\t\t\t// If "name" is an array of keys... +\t\t\t\t// When data is initially created, via ("key", "val") signature, +\t\t\t\t// keys will be converted to camelCase. +\t\t\t\t// Since there is no way to tell _how_ a key was added, remove +\t\t\t\t// both plain key and camelCase key. #12786 +\t\t\t\t// This will only penalize the array argument path. +\t\t\t\tname = name.concat( jQuery.map( name, jQuery.camelCase ) ); +\t\t\t} + +\t\t\tfor ( i = 0, l = name.length; i < l; i++ ) { +\t\t\t\tdelete thisCache[ name[i] ]; +\t\t\t} + +\t\t\t// If there is no data left in the cache, we want to continue +\t\t\t// and let the cache object itself get destroyed +\t\t\tif ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { +\t\t\t\treturn; +\t\t\t} +\t\t} +\t} + +\t// See jQuery.data for more information +\tif ( !pvt ) { +\t\tdelete cache[ id ].data; + +\t\t// Don't destroy the parent cache unless the internal data object +\t\t// had been the only thing left in it +\t\tif ( !isEmptyDataObject( cache[ id ] ) ) { +\t\t\treturn; +\t\t} +\t} + +\t// Destroy the cache +\tif ( isNode ) { +\t\tjQuery.cleanData( [ elem ], true ); + +\t// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) +\t} else if ( jQuery.support.deleteExpando || cache != cache.window ) { +\t\tdelete cache[ id ]; + +\t// When all else fails, null +\t} else { +\t\tcache[ id ] = null; +\t} } jQuery.extend({ - cache: {}, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data ) { - return internalData( elem, name, data ); - }, - - removeData: function( elem, name ) { - return internalRemoveData( elem, name ); - }, - - // For internal use only. - _data: function( elem, name, data ) { - return internalData( elem, name, data, true ); - }, - - _removeData: function( elem, name ) { - return internalRemoveData( elem, name, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - // Do not set data on non-element because it will not be cleared (#8335). - if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { - return false; - } - - var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; - - // nodes accept data unless otherwise specified; rejection can be conditional - return !noData || noData !== true && elem.getAttribute("classid") === noData; - } +\tcache: {}, + +\t// Unique for each copy of jQuery on the page +\t// Non-digits removed to match rinlinejQuery +\texpando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), + +\t// The following elements throw uncatchable exceptions if you +\t// attempt to add expando properties to them. +\tnoData: { +\t\t"embed": true, +\t\t// Ban all objects except for Flash (which handle expandos) +\t\t"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", +\t\t"applet": true +\t}, + +\thasData: function( elem ) { +\t\telem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; +\t\treturn !!elem && !isEmptyDataObject( elem ); +\t}, + +\tdata: function( elem, name, data ) { +\t\treturn internalData( elem, name, data ); +\t}, + +\tremoveData: function( elem, name ) { +\t\treturn internalRemoveData( elem, name ); +\t}, + +\t// For internal use only. +\t_data: function( elem, name, data ) { +\t\treturn internalData( elem, name, data, true ); +\t}, + +\t_removeData: function( elem, name ) { +\t\treturn internalRemoveData( elem, name, true ); +\t}, + +\t// A method for determining if a DOM node can handle the data expando +\tacceptData: function( elem ) { +\t\t// Do not set data on non-element because it will not be cleared (#8335). +\t\tif ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { +\t\t\treturn false; +\t\t} + +\t\tvar noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + +\t\t// nodes accept data unless otherwise specified; rejection can be conditional +\t\treturn !noData || noData !== true && elem.getAttribute("classid") === noData; +\t} }); jQuery.fn.extend({ - data: function( key, value ) { - var attrs, name, - elem = this[0], - i = 0, - data = null; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); - - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - attrs = elem.attributes; - for ( ; i < attrs.length; i++ ) { - name = attrs[i].name; - - if ( !name.indexOf( "data-" ) ) { - name = jQuery.camelCase( name.slice(5) ); - - dataAttr( elem, name, data[ name ] ); - } - } - jQuery._data( elem, "parsedAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - return jQuery.access( this, function( value ) { - - if ( value === undefined ) { - // Try to fetch any internally stored data first - return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; - } - - this.each(function() { - jQuery.data( this, key, value ); - }); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } +\tdata: function( key, value ) { +\t\tvar attrs, name, +\t\t\telem = this[0], +\t\t\ti = 0, +\t\t\tdata = null; + +\t\t// Gets all values +\t\tif ( key === undefined ) { +\t\t\tif ( this.length ) { +\t\t\t\tdata = jQuery.data( elem ); + +\t\t\t\tif ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { +\t\t\t\t\tattrs = elem.attributes; +\t\t\t\t\tfor ( ; i < attrs.length; i++ ) { +\t\t\t\t\t\tname = attrs[i].name; + +\t\t\t\t\t\tif ( !name.indexOf( "data-" ) ) { +\t\t\t\t\t\t\tname = jQuery.camelCase( name.slice(5) ); + +\t\t\t\t\t\t\tdataAttr( elem, name, data[ name ] ); +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t\tjQuery._data( elem, "parsedAttrs", true ); +\t\t\t\t} +\t\t\t} + +\t\t\treturn data; +\t\t} + +\t\t// Sets multiple values +\t\tif ( typeof key === "object" ) { +\t\t\treturn this.each(function() { +\t\t\t\tjQuery.data( this, key ); +\t\t\t}); +\t\t} + +\t\treturn jQuery.access( this, function( value ) { + +\t\t\tif ( value === undefined ) { +\t\t\t\t// Try to fetch any internally stored data first +\t\t\t\treturn elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; +\t\t\t} + +\t\t\tthis.each(function() { +\t\t\t\tjQuery.data( this, key, value ); +\t\t\t}); +\t\t}, null, value, arguments.length > 1, null, true ); +\t}, + +\tremoveData: function( key ) { +\t\treturn this.each(function() { +\t\t\tjQuery.removeData( this, key ); +\t\t}); +\t} }); function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; +\t// If nothing was found internally, try to fetch any +\t// data from the HTML5 data-* attribute +\tif ( data === undefined && elem.nodeType === 1 ) { + +\t\tvar name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + +\t\tdata = elem.getAttribute( name ); + +\t\tif ( typeof data === "string" ) { +\t\t\ttry { +\t\t\t\tdata = data === "true" ? true : +\t\t\t\t\tdata === "false" ? false : +\t\t\t\t\tdata === "null" ? null : +\t\t\t\t\t// Only convert to a number if it doesn't change the string +\t\t\t\t\t+data + "" === data ? +data : +\t\t\t\t\trbrace.test( data ) ? jQuery.parseJSON( data ) : +\t\t\t\t\t\tdata; +\t\t\t} catch( e ) {} + +\t\t\t// Make sure we set the data so it isn't changed later +\t\t\tjQuery.data( elem, key, data ); + +\t\t} else { +\t\t\tdata = undefined; +\t\t} +\t} + +\treturn data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { - var name; - for ( name in obj ) { - - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } - - return true; +\tvar name; +\tfor ( name in obj ) { + +\t\t// if the public data object is empty, the private is still empty +\t\tif ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { +\t\t\tcontinue; +\t\t} +\t\tif ( name !== "toJSON" ) { +\t\t\treturn false; +\t\t} +\t} + +\treturn true; } jQuery.extend({ - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray(data) ) { - queue = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - hooks.cur = fn; - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // not intended for public consumption - generates a queueHooks object, or returns the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return jQuery._data( elem, key ) || jQuery._data( elem, key, { - empty: jQuery.Callbacks("once memory").add(function() { - jQuery._removeData( elem, type + "queue" ); - jQuery._removeData( elem, key ); - }) - }); - } +\tqueue: function( elem, type, data ) { +\t\tvar queue; + +\t\tif ( elem ) { +\t\t\ttype = ( type || "fx" ) + "queue"; +\t\t\tqueue = jQuery._data( elem, type ); + +\t\t\t// Speed up dequeue by getting out quickly if this is just a lookup +\t\t\tif ( data ) { +\t\t\t\tif ( !queue || jQuery.isArray(data) ) { +\t\t\t\t\tqueue = jQuery._data( elem, type, jQuery.makeArray(data) ); +\t\t\t\t} else { +\t\t\t\t\tqueue.push( data ); +\t\t\t\t} +\t\t\t} +\t\t\treturn queue || []; +\t\t} +\t}, + +\tdequeue: function( elem, type ) { +\t\ttype = type || "fx"; + +\t\tvar queue = jQuery.queue( elem, type ), +\t\t\tstartLength = queue.length, +\t\t\tfn = queue.shift(), +\t\t\thooks = jQuery._queueHooks( elem, type ), +\t\t\tnext = function() { +\t\t\t\tjQuery.dequeue( elem, type ); +\t\t\t}; + +\t\t// If the fx queue is dequeued, always remove the progress sentinel +\t\tif ( fn === "inprogress" ) { +\t\t\tfn = queue.shift(); +\t\t\tstartLength--; +\t\t} + +\t\thooks.cur = fn; +\t\tif ( fn ) { + +\t\t\t// Add a progress sentinel to prevent the fx queue from being +\t\t\t// automatically dequeued +\t\t\tif ( type === "fx" ) { +\t\t\t\tqueue.unshift( "inprogress" ); +\t\t\t} + +\t\t\t// clear up the last queue stop function +\t\t\tdelete hooks.stop; +\t\t\tfn.call( elem, next, hooks ); +\t\t} + +\t\tif ( !startLength && hooks ) { +\t\t\thooks.empty.fire(); +\t\t} +\t}, + +\t// not intended for public consumption - generates a queueHooks object, or returns the current one +\t_queueHooks: function( elem, type ) { +\t\tvar key = type + "queueHooks"; +\t\treturn jQuery._data( elem, key ) || jQuery._data( elem, key, { +\t\t\tempty: jQuery.Callbacks("once memory").add(function() { +\t\t\t\tjQuery._removeData( elem, type + "queue" ); +\t\t\t\tjQuery._removeData( elem, key ); +\t\t\t}) +\t\t}); +\t} }); jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - // ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while( i-- ) { - tmp = jQuery._data( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } +\tqueue: function( type, data ) { +\t\tvar setter = 2; + +\t\tif ( typeof type !== "string" ) { +\t\t\tdata = type; +\t\t\ttype = "fx"; +\t\t\tsetter--; +\t\t} + +\t\tif ( arguments.length < setter ) { +\t\t\treturn jQuery.queue( this[0], type ); +\t\t} + +\t\treturn data === undefined ? +\t\t\tthis : +\t\t\tthis.each(function() { +\t\t\t\tvar queue = jQuery.queue( this, type, data ); + +\t\t\t\t// ensure a hooks for this queue +\t\t\t\tjQuery._queueHooks( this, type ); + +\t\t\t\tif ( type === "fx" && queue[0] !== "inprogress" ) { +\t\t\t\t\tjQuery.dequeue( this, type ); +\t\t\t\t} +\t\t\t}); +\t}, +\tdequeue: function( type ) { +\t\treturn this.each(function() { +\t\t\tjQuery.dequeue( this, type ); +\t\t}); +\t}, +\t// Based off of the plugin by Clint Helfers, with permission. +\t// http://blindsignals.com/index.php/2009/07/jquery-delay/ +\tdelay: function( time, type ) { +\t\ttime = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; +\t\ttype = type || "fx"; + +\t\treturn this.queue( type, function( next, hooks ) { +\t\t\tvar timeout = setTimeout( next, time ); +\t\t\thooks.stop = function() { +\t\t\t\tclearTimeout( timeout ); +\t\t\t}; +\t\t}); +\t}, +\tclearQueue: function( type ) { +\t\treturn this.queue( type || "fx", [] ); +\t}, +\t// Get a promise resolved when queues of a certain type +\t// are emptied (fx is the type by default) +\tpromise: function( type, obj ) { +\t\tvar tmp, +\t\t\tcount = 1, +\t\t\tdefer = jQuery.Deferred(), +\t\t\telements = this, +\t\t\ti = this.length, +\t\t\tresolve = function() { +\t\t\t\tif ( !( --count ) ) { +\t\t\t\t\tdefer.resolveWith( elements, [ elements ] ); +\t\t\t\t} +\t\t\t}; + +\t\tif ( typeof type !== "string" ) { +\t\t\tobj = type; +\t\t\ttype = undefined; +\t\t} +\t\ttype = type || "fx"; + +\t\twhile( i-- ) { +\t\t\ttmp = jQuery._data( elements[ i ], type + "queueHooks" ); +\t\t\tif ( tmp && tmp.empty ) { +\t\t\t\tcount++; +\t\t\t\ttmp.empty.add( resolve ); +\t\t\t} +\t\t} +\t\tresolve(); +\t\treturn defer.promise( obj ); +\t} }); var nodeHook, boolHook, - rclass = /[\t\r\n]/g, - rreturn = /\r/g, - rfocusable = /^(?:input|select|textarea|button|object)$/i, - rclickable = /^(?:a|area)$/i, - rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, - ruseDefault = /^(?:checked|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - getSetInput = jQuery.support.input; +\trclass = /[\t\r\n]/g, +\trreturn = /\r/g, +\trfocusable = /^(?:input|select|textarea|button|object)$/i, +\trclickable = /^(?:a|area)$/i, +\trboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, +\truseDefault = /^(?:checked|selected)$/i, +\tgetSetAttribute = jQuery.support.getSetAttribute, +\tgetSetInput = jQuery.support.input; jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = typeof value === "string" && value; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call( this, j, this.className ) ); - }); - } - - if ( proceed ) { - // The disjunction here is for better compressibility (see removeClass) - classes = ( value || "" ).match( core_rnotwhite ) || []; - - for ( ; i < len; i++ ) { - elem = this[ i ]; - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - " " - ); - - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - elem.className = jQuery.trim( cur ); - - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = arguments.length === 0 || typeof value === "string" && value; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call( this, j, this.className ) ); - }); - } - if ( proceed ) { - classes = ( value || "" ).match( core_rnotwhite ) || []; - - for ( ; i < len; i++ ) { - elem = this[ i ]; - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - "" - ); - - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - elem.className = value ? jQuery.trim( cur ) : ""; - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.match( core_rnotwhite ) || []; - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space separated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - // Toggle whole class name - } else if ( type === core_strundefined || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // If the element has a class name or if we're passed "false", - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var ret, hooks, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var val, - self = jQuery(this); - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } +\tattr: function( name, value ) { +\t\treturn jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); +\t}, + +\tremoveAttr: function( name ) { +\t\treturn this.each(function() { +\t\t\tjQuery.removeAttr( this, name ); +\t\t}); +\t}, + +\tprop: function( name, value ) { +\t\treturn jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); +\t}, + +\tremoveProp: function( name ) { +\t\tname = jQuery.propFix[ name ] || name; +\t\treturn this.each(function() { +\t\t\t// try/catch handles cases where IE balks (such as removing a property on window) +\t\t\ttry { +\t\t\t\tthis[ name ] = undefined; +\t\t\t\tdelete this[ name ]; +\t\t\t} catch( e ) {} +\t\t}); +\t}, + +\taddClass: function( value ) { +\t\tvar classes, elem, cur, clazz, j, +\t\t\ti = 0, +\t\t\tlen = this.length, +\t\t\tproceed = typeof value === "string" && value; + +\t\tif ( jQuery.isFunction( value ) ) { +\t\t\treturn this.each(function( j ) { +\t\t\t\tjQuery( this ).addClass( value.call( this, j, this.className ) ); +\t\t\t}); +\t\t} + +\t\tif ( proceed ) { +\t\t\t// The disjunction here is for better compressibility (see removeClass) +\t\t\tclasses = ( value || "" ).match( core_rnotwhite ) || []; + +\t\t\tfor ( ; i < len; i++ ) { +\t\t\t\telem = this[ i ]; +\t\t\t\tcur = elem.nodeType === 1 && ( elem.className ? +\t\t\t\t\t( " " + elem.className + " " ).replace( rclass, " " ) : +\t\t\t\t\t" " +\t\t\t\t); + +\t\t\t\tif ( cur ) { +\t\t\t\t\tj = 0; +\t\t\t\t\twhile ( (clazz = classes[j++]) ) { +\t\t\t\t\t\tif ( cur.indexOf( " " + clazz + " " ) < 0 ) { +\t\t\t\t\t\t\tcur += clazz + " "; +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t\telem.className = jQuery.trim( cur ); + +\t\t\t\t} +\t\t\t} +\t\t} + +\t\treturn this; +\t}, + +\tremoveClass: function( value ) { +\t\tvar classes, elem, cur, clazz, j, +\t\t\ti = 0, +\t\t\tlen = this.length, +\t\t\tproceed = arguments.length === 0 || typeof value === "string" && value; + +\t\tif ( jQuery.isFunction( value ) ) { +\t\t\treturn this.each(function( j ) { +\t\t\t\tjQuery( this ).removeClass( value.call( this, j, this.className ) ); +\t\t\t}); +\t\t} +\t\tif ( proceed ) { +\t\t\tclasses = ( value || "" ).match( core_rnotwhite ) || []; + +\t\t\tfor ( ; i < len; i++ ) { +\t\t\t\telem = this[ i ]; +\t\t\t\t// This expression is here for better compressibility (see addClass) +\t\t\t\tcur = elem.nodeType === 1 && ( elem.className ? +\t\t\t\t\t( " " + elem.className + " " ).replace( rclass, " " ) : +\t\t\t\t\t"" +\t\t\t\t); + +\t\t\t\tif ( cur ) { +\t\t\t\t\tj = 0; +\t\t\t\t\twhile ( (clazz = classes[j++]) ) { +\t\t\t\t\t\t// Remove *all* instances +\t\t\t\t\t\twhile ( cur.indexOf( " " + clazz + " " ) >= 0 ) { +\t\t\t\t\t\t\tcur = cur.replace( " " + clazz + " ", " " ); +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t\telem.className = value ? jQuery.trim( cur ) : ""; +\t\t\t\t} +\t\t\t} +\t\t} + +\t\treturn this; +\t}, + +\ttoggleClass: function( value, stateVal ) { +\t\tvar type = typeof value, +\t\t\tisBool = typeof stateVal === "boolean"; + +\t\tif ( jQuery.isFunction( value ) ) { +\t\t\treturn this.each(function( i ) { +\t\t\t\tjQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); +\t\t\t}); +\t\t} + +\t\treturn this.each(function() { +\t\t\tif ( type === "string" ) { +\t\t\t\t// toggle individual class names +\t\t\t\tvar className, +\t\t\t\t\ti = 0, +\t\t\t\t\tself = jQuery( this ), +\t\t\t\t\tstate = stateVal, +\t\t\t\t\tclassNames = value.match( core_rnotwhite ) || []; + +\t\t\t\twhile ( (className = classNames[ i++ ]) ) { +\t\t\t\t\t// check each className given, space separated list +\t\t\t\t\tstate = isBool ? state : !self.hasClass( className ); +\t\t\t\t\tself[ state ? "addClass" : "removeClass" ]( className ); +\t\t\t\t} + +\t\t\t// Toggle whole class name +\t\t\t} else if ( type === core_strundefined || type === "boolean" ) { +\t\t\t\tif ( this.className ) { +\t\t\t\t\t// store className if set +\t\t\t\t\tjQuery._data( this, "__className__", this.className ); +\t\t\t\t} + +\t\t\t\t// If the element has a class name or if we're passed "false", +\t\t\t\t// then remove the whole classname (if there was one, the above saved it). +\t\t\t\t// Otherwise bring back whatever was previously saved (if anything), +\t\t\t\t// falling back to the empty string if nothing was stored. +\t\t\t\tthis.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; +\t\t\t} +\t\t}); +\t}, + +\thasClass: function( selector ) { +\t\tvar className = " " + selector + " ", +\t\t\ti = 0, +\t\t\tl = this.length; +\t\tfor ( ; i < l; i++ ) { +\t\t\tif ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { +\t\t\t\treturn true; +\t\t\t} +\t\t} + +\t\treturn false; +\t}, + +\tval: function( value ) { +\t\tvar ret, hooks, isFunction, +\t\t\telem = this[0]; + +\t\tif ( !arguments.length ) { +\t\t\tif ( elem ) { +\t\t\t\thooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + +\t\t\t\tif ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { +\t\t\t\t\treturn ret; +\t\t\t\t} + +\t\t\t\tret = elem.value; + +\t\t\t\treturn typeof ret === "string" ? +\t\t\t\t\t// handle most common string cases +\t\t\t\t\tret.replace(rreturn, "") : +\t\t\t\t\t// handle cases where value is null/undef or number +\t\t\t\t\tret == null ? "" : ret; +\t\t\t} + +\t\t\treturn; +\t\t} + +\t\tisFunction = jQuery.isFunction( value ); + +\t\treturn this.each(function( i ) { +\t\t\tvar val, +\t\t\t\tself = jQuery(this); + +\t\t\tif ( this.nodeType !== 1 ) { +\t\t\t\treturn; +\t\t\t} + +\t\t\tif ( isFunction ) { +\t\t\t\tval = value.call( this, i, self.val() ); +\t\t\t} else { +\t\t\t\tval = value; +\t\t\t} + +\t\t\t// Treat null/undefined as ""; convert numbers to string +\t\t\tif ( val == null ) { +\t\t\t\tval = ""; +\t\t\t} else if ( typeof val === "number" ) { +\t\t\t\tval += ""; +\t\t\t} else if ( jQuery.isArray( val ) ) { +\t\t\t\tval = jQuery.map(val, function ( value ) { +\t\t\t\t\treturn value == null ? "" : value + ""; +\t\t\t\t}); +\t\t\t} + +\t\t\thooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + +\t\t\t// If set returns undefined, fall back to normal setting +\t\t\tif ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { +\t\t\t\tthis.value = val; +\t\t\t} +\t\t}); +\t} }); jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, option, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one" || index < 0, - values = one ? null : [], - max = one ? index + 1 : options.length, - i = index < 0 ? - max : - one ? index : 0; - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // oldIE doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - // Don't return options that are disabled or in a disabled optgroup - ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && - ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attr: function( elem, name, value ) { - var hooks, notxml, ret, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === core_strundefined ) { - return jQuery.prop( elem, name, value ); - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - - } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, value + "" ); - return value; - } - - } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - // In IE9+, Flash objects don't have .getAttribute (#12945) - // Support: IE9+ - if ( typeof elem.getAttribute !== core_strundefined ) { - ret = elem.getAttribute( name ); - } - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var name, propName, - i = 0, - attrNames = value && value.match( core_rnotwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( (name = attrNames[i++]) ) { - propName = jQuery.propFix[ name ] || name; - - // Boolean attributes get special treatment (#10870) - if ( rboolean.test( name ) ) { - // Set corresponding property to false for boolean attributes - // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 - if ( !getSetAttribute && ruseDefault.test( name ) ) { - elem[ jQuery.camelCase( "default-" + name ) ] = - elem[ propName ] = false; - } else { - elem[ propName ] = false; - } - - // See #9699 for explanation of this approach (setting first, then removal) - } else { - jQuery.attr( elem, name, "" ); - } - - elem.removeAttribute( getSetAttribute ? name : propName ); - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to default in case type is set after value during creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return ( elem[ name ] = value ); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - } - } +\tvalHooks: { +\t\toption: { +\t\t\tget: function( elem ) { +\t\t\t\t// attributes.value is undefined in Blackberry 4.7 but +\t\t\t\t// uses .value. See #6932 +\t\t\t\tvar val = elem.attributes.value; +\t\t\t\treturn !val || val.specified ? elem.value : elem.text; +\t\t\t} +\t\t}, +\t\tselect: { +\t\t\tget: function( elem ) { +\t\t\t\tvar value, option, +\t\t\t\t\toptions = elem.options, +\t\t\t\t\tindex = elem.selectedIndex, +\t\t\t\t\tone = elem.type === "select-one" || index < 0, +\t\t\t\t\tvalues = one ? null : [], +\t\t\t\t\tmax = one ? index + 1 : options.length, +\t\t\t\t\ti = index < 0 ? +\t\t\t\t\t\tmax : +\t\t\t\t\t\tone ? index : 0; + +\t\t\t\t// Loop through all the selected options +\t\t\t\tfor ( ; i < max; i++ ) { +\t\t\t\t\toption = options[ i ]; + +\t\t\t\t\t// oldIE doesn't update selected after form reset (#2551) +\t\t\t\t\tif ( ( option.selected || i === index ) && +\t\t\t\t\t\t\t// Don't return options that are disabled or in a disabled optgroup +\t\t\t\t\t\t\t( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && +\t\t\t\t\t\t\t( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + +\t\t\t\t\t\t// Get the specific value for the option +\t\t\t\t\t\tvalue = jQuery( option ).val(); + +\t\t\t\t\t\t// We don't need an array for one selects +\t\t\t\t\t\tif ( one ) { +\t\t\t\t\t\t\treturn value; +\t\t\t\t\t\t} + +\t\t\t\t\t\t// Multi-Selects return an array +\t\t\t\t\t\tvalues.push( value ); +\t\t\t\t\t} +\t\t\t\t} + +\t\t\t\treturn values; +\t\t\t}, + +\t\t\tset: function( elem, value ) { +\t\t\t\tvar values = jQuery.makeArray( value ); + +\t\t\t\tjQuery(elem).find("option").each(function() { +\t\t\t\t\tthis.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; +\t\t\t\t}); + +\t\t\t\tif ( !values.length ) { +\t\t\t\t\telem.selectedIndex = -1; +\t\t\t\t} +\t\t\t\treturn values; +\t\t\t} +\t\t} +\t}, + +\tattr: function( elem, name, value ) { +\t\tvar hooks, notxml, ret, +\t\t\tnType = elem.nodeType; + +\t\t// don't get/set attributes on text, comment and attribute nodes +\t\tif ( !elem || nType === 3 || nType === 8 || nType === 2 ) { +\t\t\treturn; +\t\t} + +\t\t// Fallback to prop when attributes are not supported +\t\tif ( typeof elem.getAttribute === core_strundefined ) { +\t\t\treturn jQuery.prop( elem, name, value ); +\t\t} + +\t\tnotxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + +\t\t// All attributes are lowercase +\t\t// Grab necessary hook if one is defined +\t\tif ( notxml ) { +\t\t\tname = name.toLowerCase(); +\t\t\thooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); +\t\t} + +\t\tif ( value !== undefined ) { + +\t\t\tif ( value === null ) { +\t\t\t\tjQuery.removeAttr( elem, name ); + +\t\t\t} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { +\t\t\t\treturn ret; + +\t\t\t} else { +\t\t\t\telem.setAttribute( name, value + "" ); +\t\t\t\treturn value; +\t\t\t} + +\t\t} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { +\t\t\treturn ret; + +\t\t} else { + +\t\t\t// In IE9+, Flash objects don't have .getAttribute (#12945) +\t\t\t// Support: IE9+ +\t\t\tif ( typeof elem.getAttribute !== core_strundefined ) { +\t\t\t\tret = elem.getAttribute( name ); +\t\t\t} + +\t\t\t// Non-existent attributes return null, we normalize to undefined +\t\t\treturn ret == null ? +\t\t\t\tundefined : +\t\t\t\tret; +\t\t} +\t}, + +\tremoveAttr: function( elem, value ) { +\t\tvar name, propName, +\t\t\ti = 0, +\t\t\tattrNames = value && value.match( core_rnotwhite ); + +\t\tif ( attrNames && elem.nodeType === 1 ) { +\t\t\twhile ( (name = attrNames[i++]) ) { +\t\t\t\tpropName = jQuery.propFix[ name ] || name; + +\t\t\t\t// Boolean attributes get special treatment (#10870) +\t\t\t\tif ( rboolean.test( name ) ) { +\t\t\t\t\t// Set corresponding property to false for boolean attributes +\t\t\t\t\t// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 +\t\t\t\t\tif ( !getSetAttribute && ruseDefault.test( name ) ) { +\t\t\t\t\t\telem[ jQuery.camelCase( "default-" + name ) ] = +\t\t\t\t\t\t\telem[ propName ] = false; +\t\t\t\t\t} else { +\t\t\t\t\t\telem[ propName ] = false; +\t\t\t\t\t} + +\t\t\t\t// See #9699 for explanation of this approach (setting first, then removal) +\t\t\t\t} else { +\t\t\t\t\tjQuery.attr( elem, name, "" ); +\t\t\t\t} + +\t\t\t\telem.removeAttribute( getSetAttribute ? name : propName ); +\t\t\t} +\t\t} +\t}, + +\tattrHooks: { +\t\ttype: { +\t\t\tset: function( elem, value ) { +\t\t\t\tif ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { +\t\t\t\t\t// Setting the type on a radio button after the value resets the value in IE6-9 +\t\t\t\t\t// Reset value to default in case type is set after value during creation +\t\t\t\t\tvar val = elem.value; +\t\t\t\t\telem.setAttribute( "type", value ); +\t\t\t\t\tif ( val ) { +\t\t\t\t\t\telem.value = val; +\t\t\t\t\t} +\t\t\t\t\treturn value; +\t\t\t\t} +\t\t\t} +\t\t} +\t}, + +\tpropFix: { +\t\ttabindex: "tabIndex", +\t\treadonly: "readOnly", +\t\t"for": "htmlFor", +\t\t"class": "className", +\t\tmaxlength: "maxLength", +\t\tcellspacing: "cellSpacing", +\t\tcellpadding: "cellPadding", +\t\trowspan: "rowSpan", +\t\tcolspan: "colSpan", +\t\tusemap: "useMap", +\t\tframeborder: "frameBorder", +\t\tcontenteditable: "contentEditable" +\t}, + +\tprop: function( elem, name, value ) { +\t\tvar ret, hooks, notxml, +\t\t\tnType = elem.nodeType; + +\t\t// don't get/set properties on text, comment and attribute nodes +\t\tif ( !elem || nType === 3 || nType === 8 || nType === 2 ) { +\t\t\treturn; +\t\t} + +\t\tnotxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + +\t\tif ( notxml ) { +\t\t\t// Fix name and attach hooks +\t\t\tname = jQuery.propFix[ name ] || name; +\t\t\thooks = jQuery.propHooks[ name ]; +\t\t} + +\t\tif ( value !== undefined ) { +\t\t\tif ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { +\t\t\t\treturn ret; + +\t\t\t} else { +\t\t\t\treturn ( elem[ name ] = value ); +\t\t\t} + +\t\t} else { +\t\t\tif ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { +\t\t\t\treturn ret; + +\t\t\t} else { +\t\t\t\treturn elem[ name ]; +\t\t\t} +\t\t} +\t}, + +\tpropHooks: { +\t\ttabIndex: { +\t\t\tget: function( elem ) { +\t\t\t\t// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set +\t\t\t\t// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ +\t\t\t\tvar attributeNode = elem.getAttributeNode("tabindex"); + +\t\t\t\treturn attributeNode && attributeNode.specified ? +\t\t\t\t\tparseInt( attributeNode.value, 10 ) : +\t\t\t\t\trfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? +\t\t\t\t\t\t0 : +\t\t\t\t\t\tundefined; +\t\t\t} +\t\t} +\t} }); // Hook for boolean attributes boolHook = { - get: function( elem, name ) { - var - // Use .prop to determine if this attribute is understood as boolean - prop = jQuery.prop( elem, name ), - - // Fetch it accordingly - attr = typeof prop === "boolean" && elem.getAttribute( name ), - detail = typeof prop === "boolean" ? - - getSetInput && getSetAttribute ? - attr != null : - // oldIE fabricates an empty string for missing boolean attributes - // and conflates checked/selected into attroperties - ruseDefault.test( name ) ? - elem[ jQuery.camelCase( "default-" + name ) ] : - !!attr : - - // fetch an attribute node for properties not recognized as boolean - elem.getAttributeNode( name ); - - return detail && detail.value !== false ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { - // IE<8 needs the *property* name - elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); - - // Use defaultChecked and defaultSelected for oldIE - } else { - elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; - } - - return name; - } +\tget: function( elem, name ) { +\t\tvar +\t\t\t// Use .prop to determine if this attribute is understood as boolean +\t\t\tprop = jQuery.prop( elem, name ), + +\t\t\t// Fetch it accordingly +\t\t\tattr = typeof prop === "boolean" && elem.getAttribute( name ), +\t\t\tdetail = typeof prop === "boolean" ? + +\t\t\t\tgetSetInput && getSetAttribute ? +\t\t\t\t\tattr != null : +\t\t\t\t\t// oldIE fabricates an empty string for missing boolean attributes +\t\t\t\t\t// and conflates checked/selected into attroperties +\t\t\t\t\truseDefault.test( name ) ? +\t\t\t\t\t\telem[ jQuery.camelCase( "default-" + name ) ] : +\t\t\t\t\t\t!!attr : + +\t\t\t\t// fetch an attribute node for properties not recognized as boolean +\t\t\t\telem.getAttributeNode( name ); + +\t\treturn detail && detail.value !== false ? +\t\t\tname.toLowerCase() : +\t\t\tundefined; +\t}, +\tset: function( elem, value, name ) { +\t\tif ( value === false ) { +\t\t\t// Remove boolean attributes when set to false +\t\t\tjQuery.removeAttr( elem, name ); +\t\t} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { +\t\t\t// IE<8 needs the *property* name +\t\t\telem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); + +\t\t// Use defaultChecked and defaultSelected for oldIE +\t\t} else { +\t\t\telem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; +\t\t} + +\t\treturn name; +\t} }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { - jQuery.attrHooks.value = { - get: function( elem, name ) { - var ret = elem.getAttributeNode( name ); - return jQuery.nodeName( elem, "input" ) ? - - // Ignore the value *property* by using defaultValue - elem.defaultValue : - - ret && ret.specified ? ret.value : undefined; - }, - set: function( elem, value, name ) { - if ( jQuery.nodeName( elem, "input" ) ) { - // Does not return so that setAttribute is also used - elem.defaultValue = value; - } else { - // Use nodeHook if defined (#1954); otherwise setAttribute is fine - return nodeHook && nodeHook.set( elem, value, name ); - } - } - }; +\tjQuery.attrHooks.value = { +\t\tget: function( elem, name ) { +\t\t\tvar ret = elem.getAttributeNode( name ); +\t\t\treturn jQuery.nodeName( elem, "input" ) ? + +\t\t\t\t// Ignore the value *property* by using defaultValue +\t\t\t\telem.defaultValue : + +\t\t\t\tret && ret.specified ? ret.value : undefined; +\t\t}, +\t\tset: function( elem, value, name ) { +\t\t\tif ( jQuery.nodeName( elem, "input" ) ) { +\t\t\t\t// Does not return so that setAttribute is also used +\t\t\t\telem.defaultValue = value; +\t\t\t} else { +\t\t\t\t// Use nodeHook if defined (#1954); otherwise setAttribute is fine +\t\t\t\treturn nodeHook && nodeHook.set( elem, value, name ); +\t\t\t} +\t\t} +\t}; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret = elem.getAttributeNode( name ); - return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? - ret.value : - undefined; - }, - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - elem.setAttributeNode( - (ret = elem.ownerDocument.createAttribute( name )) - ); - } - - ret.value = value += ""; - - // Break association with cloned elements by also using setAttribute (#9646) - return name === "value" || value === elem.getAttribute( name ) ? - value : - undefined; - } - }; - - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - nodeHook.set( elem, value === "" ? false : value, name ); - } - }; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); +\t// Use this for any attribute in IE6/7 +\t// This fixes almost every IE6/7 issue +\tnodeHook = jQuery.valHooks.button = { +\t\tget: function( elem, name ) { +\t\t\tvar ret = elem.getAttributeNode( name ); +\t\t\treturn ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? +\t\t\t\tret.value : +\t\t\t\tundefined; +\t\t}, +\t\tset: function( elem, value, name ) { +\t\t\t// Set the existing or create a new attribute node +\t\t\tvar ret = elem.getAttributeNode( name ); +\t\t\tif ( !ret ) { +\t\t\t\telem.setAttributeNode( +\t\t\t\t\t(ret = elem.ownerDocument.createAttribute( name )) +\t\t\t\t); +\t\t\t} + +\t\t\tret.value = value += ""; + +\t\t\t// Break association with cloned elements by also using setAttribute (#9646) +\t\t\treturn name === "value" || value === elem.getAttribute( name ) ? +\t\t\t\tvalue : +\t\t\t\tundefined; +\t\t} +\t}; + +\t// Set contenteditable to false on removals(#10429) +\t// Setting to empty string throws an error as an invalid value +\tjQuery.attrHooks.contenteditable = { +\t\tget: nodeHook.get, +\t\tset: function( elem, value, name ) { +\t\t\tnodeHook.set( elem, value === "" ? false : value, name ); +\t\t} +\t}; + +\t// Set width and height to auto instead of 0 on empty string( Bug #8150 ) +\t// This is for removals +\tjQuery.each([ "width", "height" ], function( i, name ) { +\t\tjQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { +\t\t\tset: function( elem, value ) { +\t\t\t\tif ( value === "" ) { +\t\t\t\t\telem.setAttribute( name, "auto" ); +\t\t\t\t\treturn value; +\t\t\t\t} +\t\t\t} +\t\t}); +\t}); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret == null ? undefined : ret; - } - }); - }); - - // href/src property should get the full normalized URL (#10299/#12915) - jQuery.each([ "href", "src" ], function( i, name ) { - jQuery.propHooks[ name ] = { - get: function( elem ) { - return elem.getAttribute( name, 4 ); - } - }; - }); +\tjQuery.each([ "href", "src", "width", "height" ], function( i, name ) { +\t\tjQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { +\t\t\tget: function( elem ) { +\t\t\t\tvar ret = elem.getAttribute( name, 2 ); +\t\t\t\treturn ret == null ? undefined : ret; +\t\t\t} +\t\t}); +\t}); + +\t// href/src property should get the full normalized URL (#10299/#12915) +\tjQuery.each([ "href", "src" ], function( i, name ) { +\t\tjQuery.propHooks[ name ] = { +\t\t\tget: function( elem ) { +\t\t\t\treturn elem.getAttribute( name, 4 ); +\t\t\t} +\t\t}; +\t}); } if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Note: IE uppercases css property names, but if we were to .toLowerCase() - // .cssText, that would destroy case senstitivity in URL's, like in "background" - return elem.style.cssText || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = value + "" ); - } - }; +\tjQuery.attrHooks.style = { +\t\tget: function( elem ) { +\t\t\t// Return undefined in the case of empty string +\t\t\t// Note: IE uppercases css property names, but if we were to .toLowerCase() +\t\t\t// .cssText, that would destroy case senstitivity in URL's, like in "background" +\t\t\treturn elem.style.cssText || undefined; +\t\t}, +\t\tset: function( elem, value ) { +\t\t\treturn ( elem.style.cssText = value + "" ); +\t\t} +\t}; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - return null; - } - }); +\tjQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { +\t\tget: function( elem ) { +\t\t\tvar parent = elem.parentNode; + +\t\t\tif ( parent ) { +\t\t\t\tparent.selectedIndex; + +\t\t\t\t// Make sure that it also works with optgroups, see #5701 +\t\t\t\tif ( parent.parentNode ) { +\t\t\t\t\tparent.parentNode.selectedIndex; +\t\t\t\t} +\t\t\t} +\t\t\treturn null; +\t\t} +\t}); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; +\tjQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); +\tjQuery.each([ "radio", "checkbox" ], function() { +\t\tjQuery.valHooks[ this ] = { +\t\t\tget: function( elem ) { +\t\t\t\t// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified +\t\t\t\treturn elem.getAttribute("value") === null ? "on" : elem.value; +\t\t\t} +\t\t}; +\t}); } jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }); +\tjQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { +\t\tset: function( elem, value ) { +\t\t\tif ( jQuery.isArray( value ) ) { +\t\t\t\treturn ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); +\t\t\t} +\t\t} +\t}); }); var rformElems = /^(?:input|select|textarea)$/i, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; +\trkeyEvent = /^key/, +\trmouseEvent = /^(?:mouse|contextmenu)|click/, +\trfocusMorph = /^(?:focusinfocus|focusoutblur)$/, +\trtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { - return true; +\treturn true; } function returnFalse() { - return false; +\treturn false; } /* @@ -2713,976 +2713,976 @@ function returnFalse() { */ jQuery.event = { - global: {}, - - add: function( elem, types, handler, data, selector ) { - var tmp, events, t, handleObjIn, - special, eventHandle, handleObj, - handlers, type, namespaces, origType, - elemData = jQuery._data( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !(events = elemData.events) ) { - events = elemData.events = {}; - } - if ( !(eventHandle = elemData.handle) ) { - eventHandle = elemData.handle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !(handlers = events[ type ]) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - var j, handleObj, tmp, - origCount, t, events, - special, handlers, type, - namespaces, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ); - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - delete elemData.handle; - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery._removeData( elem, "events" ); - } - }, - - trigger: function( event, data, elem, onlyHandlers ) { - var handle, ontype, cur, - bubbleType, special, tmp, i, - eventPath = [ elem || document ], - type = core_hasOwn.call( event, "type" ) ? event.type : event, - namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; - - cur = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf(":") < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - event.isTrigger = true; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === (elem.ownerDocument || document) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { - - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - try { - elem[ type ](); - } catch ( e ) { - // IE<9 dies on focus/blur to hidden element (#1486,#12518) - // only reproducible on winXP IE8 native, not IE9 in IE8 mode - } - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); - - var i, ret, handleObj, matched, j, - handlerQueue = [], - args = core_slice.call( arguments ), - handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( (event.result = ret) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var sel, handleObj, matches, i, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { - - for ( ; cur != this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) >= 0 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, handlers: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); - } - - return handlerQueue; - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; - - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; - } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = new jQuery.Event( originalEvent ); - - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Support: IE<9 - // Fix target property (#1925) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } - - // Support: Chrome 23+, Safari? - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // Support: IE<9 - // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) - event.metaKey = !!event.metaKey; - - return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var body, eventDoc, doc, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - special: { - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - click: { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { - this.click(); - return false; - } - } - }, - focus: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== document.activeElement && this.focus ) { - try { - this.focus(); - return false; - } catch ( e ) { - // Support: IE<9 - // If we error on focus to hidden element (#1486, #12518), - // let .trigger() run the handlers - } - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === document.activeElement && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - - beforeunload: { - postDispatch: function( event ) { - - // Even when returnValue equals to undefined Firefox will still show alert - if ( event.result !== undefined ) { - event.originalEvent.returnValue = event.result; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } +\tglobal: {}, + +\tadd: function( elem, types, handler, data, selector ) { +\t\tvar tmp, events, t, handleObjIn, +\t\t\tspecial, eventHandle, handleObj, +\t\t\thandlers, type, namespaces, origType, +\t\t\telemData = jQuery._data( elem ); + +\t\t// Don't attach events to noData or text/comment nodes (but allow plain objects) +\t\tif ( !elemData ) { +\t\t\treturn; +\t\t} + +\t\t// Caller can pass in an object of custom data in lieu of the handler +\t\tif ( handler.handler ) { +\t\t\thandleObjIn = handler; +\t\t\thandler = handleObjIn.handler; +\t\t\tselector = handleObjIn.selector; +\t\t} + +\t\t// Make sure that the handler has a unique ID, used to find/remove it later +\t\tif ( !handler.guid ) { +\t\t\thandler.guid = jQuery.guid++; +\t\t} + +\t\t// Init the element's event structure and main handler, if this is the first +\t\tif ( !(events = elemData.events) ) { +\t\t\tevents = elemData.events = {}; +\t\t} +\t\tif ( !(eventHandle = elemData.handle) ) { +\t\t\teventHandle = elemData.handle = function( e ) { +\t\t\t\t// Discard the second event of a jQuery.event.trigger() and +\t\t\t\t// when an event is called after a page has unloaded +\t\t\t\treturn typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? +\t\t\t\t\tjQuery.event.dispatch.apply( eventHandle.elem, arguments ) : +\t\t\t\t\tundefined; +\t\t\t}; +\t\t\t// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events +\t\t\teventHandle.elem = elem; +\t\t} + +\t\t// Handle multiple events separated by a space +\t\t// jQuery(...).bind("mouseover mouseout", fn); +\t\ttypes = ( types || "" ).match( core_rnotwhite ) || [""]; +\t\tt = types.length; +\t\twhile ( t-- ) { +\t\t\ttmp = rtypenamespace.exec( types[t] ) || []; +\t\t\ttype = origType = tmp[1]; +\t\t\tnamespaces = ( tmp[2] || "" ).split( "." ).sort(); + +\t\t\t// If event changes its type, use the special event handlers for the changed type +\t\t\tspecial = jQuery.event.special[ type ] || {}; + +\t\t\t// If selector defined, determine special event api type, otherwise given type +\t\t\ttype = ( selector ? special.delegateType : special.bindType ) || type; + +\t\t\t// Update special based on newly reset type +\t\t\tspecial = jQuery.event.special[ type ] || {}; + +\t\t\t// handleObj is passed to all event handlers +\t\t\thandleObj = jQuery.extend({ +\t\t\t\ttype: type, +\t\t\t\torigType: origType, +\t\t\t\tdata: data, +\t\t\t\thandler: handler, +\t\t\t\tguid: handler.guid, +\t\t\t\tselector: selector, +\t\t\t\tneedsContext: selector && jQuery.expr.match.needsContext.test( selector ), +\t\t\t\tnamespace: namespaces.join(".") +\t\t\t}, handleObjIn ); + +\t\t\t// Init the event handler queue if we're the first +\t\t\tif ( !(handlers = events[ type ]) ) { +\t\t\t\thandlers = events[ type ] = []; +\t\t\t\thandlers.delegateCount = 0; + +\t\t\t\t// Only use addEventListener/attachEvent if the special events handler returns false +\t\t\t\tif ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { +\t\t\t\t\t// Bind the global event handler to the element +\t\t\t\t\tif ( elem.addEventListener ) { +\t\t\t\t\t\telem.addEventListener( type, eventHandle, false ); + +\t\t\t\t\t} else if ( elem.attachEvent ) { +\t\t\t\t\t\telem.attachEvent( "on" + type, eventHandle ); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} + +\t\t\tif ( special.add ) { +\t\t\t\tspecial.add.call( elem, handleObj ); + +\t\t\t\tif ( !handleObj.handler.guid ) { +\t\t\t\t\thandleObj.handler.guid = handler.guid; +\t\t\t\t} +\t\t\t} + +\t\t\t// Add to the element's handler list, delegates in front +\t\t\tif ( selector ) { +\t\t\t\thandlers.splice( handlers.delegateCount++, 0, handleObj ); +\t\t\t} else { +\t\t\t\thandlers.push( handleObj ); +\t\t\t} + +\t\t\t// Keep track of which events have ever been used, for event optimization +\t\t\tjQuery.event.global[ type ] = true; +\t\t} + +\t\t// Nullify elem to prevent memory leaks in IE +\t\telem = null; +\t}, + +\t// Detach an event or set of events from an element +\tremove: function( elem, types, handler, selector, mappedTypes ) { +\t\tvar j, handleObj, tmp, +\t\t\torigCount, t, events, +\t\t\tspecial, handlers, type, +\t\t\tnamespaces, origType, +\t\t\telemData = jQuery.hasData( elem ) && jQuery._data( elem ); + +\t\tif ( !elemData || !(events = elemData.events) ) { +\t\t\treturn; +\t\t} + +\t\t// Once for each type.namespace in types; type may be omitted +\t\ttypes = ( types || "" ).match( core_rnotwhite ) || [""]; +\t\tt = types.length; +\t\twhile ( t-- ) { +\t\t\ttmp = rtypenamespace.exec( types[t] ) || []; +\t\t\ttype = origType = tmp[1]; +\t\t\tnamespaces = ( tmp[2] || "" ).split( "." ).sort(); + +\t\t\t// Unbind all events (on this namespace, if provided) for the element +\t\t\tif ( !type ) { +\t\t\t\tfor ( type in events ) { +\t\t\t\t\tjQuery.event.remove( elem, type + types[ t ], handler, selector, true ); +\t\t\t\t} +\t\t\t\tcontinue; +\t\t\t} + +\t\t\tspecial = jQuery.event.special[ type ] || {}; +\t\t\ttype = ( selector ? special.delegateType : special.bindType ) || type; +\t\t\thandlers = events[ type ] || []; +\t\t\ttmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + +\t\t\t// Remove matching events +\t\t\torigCount = j = handlers.length; +\t\t\twhile ( j-- ) { +\t\t\t\thandleObj = handlers[ j ]; + +\t\t\t\tif ( ( mappedTypes || origType === handleObj.origType ) && +\t\t\t\t\t( !handler || handler.guid === handleObj.guid ) && +\t\t\t\t\t( !tmp || tmp.test( handleObj.namespace ) ) && +\t\t\t\t\t( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { +\t\t\t\t\thandlers.splice( j, 1 ); + +\t\t\t\t\tif ( handleObj.selector ) { +\t\t\t\t\t\thandlers.delegateCount--; +\t\t\t\t\t} +\t\t\t\t\tif ( special.remove ) { +\t\t\t\t\t\tspecial.remove.call( elem, handleObj ); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} + +\t\t\t// Remove generic event handler if we removed something and no more handlers exist +\t\t\t// (avoids potential for endless recursion during removal of special event handlers) +\t\t\tif ( origCount && !handlers.length ) { +\t\t\t\tif ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { +\t\t\t\t\tjQuery.removeEvent( elem, type, elemData.handle ); +\t\t\t\t} + +\t\t\t\tdelete events[ type ]; +\t\t\t} +\t\t} + +\t\t// Remove the expando if it's no longer used +\t\tif ( jQuery.isEmptyObject( events ) ) { +\t\t\tdelete elemData.handle; + +\t\t\t// removeData also checks for emptiness and clears the expando if empty +\t\t\t// so use it instead of delete +\t\t\tjQuery._removeData( elem, "events" ); +\t\t} +\t}, + +\ttrigger: function( event, data, elem, onlyHandlers ) { +\t\tvar handle, ontype, cur, +\t\t\tbubbleType, special, tmp, i, +\t\t\teventPath = [ elem || document ], +\t\t\ttype = core_hasOwn.call( event, "type" ) ? event.type : event, +\t\t\tnamespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + +\t\tcur = tmp = elem = elem || document; + +\t\t// Don't do events on text and comment nodes +\t\tif ( elem.nodeType === 3 || elem.nodeType === 8 ) { +\t\t\treturn; +\t\t} + +\t\t// focus/blur morphs to focusin/out; ensure we're not firing them right now +\t\tif ( rfocusMorph.test( type + jQuery.event.triggered ) ) { +\t\t\treturn; +\t\t} + +\t\tif ( type.indexOf(".") >= 0 ) { +\t\t\t// Namespaced trigger; create a regexp to match event type in handle() +\t\t\tnamespaces = type.split("."); +\t\t\ttype = namespaces.shift(); +\t\t\tnamespaces.sort(); +\t\t} +\t\tontype = type.indexOf(":") < 0 && "on" + type; + +\t\t// Caller can pass in a jQuery.Event object, Object, or just an event type string +\t\tevent = event[ jQuery.expando ] ? +\t\t\tevent : +\t\t\tnew jQuery.Event( type, typeof event === "object" && event ); + +\t\tevent.isTrigger = true; +\t\tevent.namespace = namespaces.join("."); +\t\tevent.namespace_re = event.namespace ? +\t\t\tnew RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : +\t\t\tnull; + +\t\t// Clean up the event in case it is being reused +\t\tevent.result = undefined; +\t\tif ( !event.target ) { +\t\t\tevent.target = elem; +\t\t} + +\t\t// Clone any incoming data and prepend the event, creating the handler arg list +\t\tdata = data == null ? +\t\t\t[ event ] : +\t\t\tjQuery.makeArray( data, [ event ] ); + +\t\t// Allow special events to draw outside the lines +\t\tspecial = jQuery.event.special[ type ] || {}; +\t\tif ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { +\t\t\treturn; +\t\t} + +\t\t// Determine event propagation path in advance, per W3C events spec (#9951) +\t\t// Bubble up to document, then to window; watch for a global ownerDocument var (#9724) +\t\tif ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + +\t\t\tbubbleType = special.delegateType || type; +\t\t\tif ( !rfocusMorph.test( bubbleType + type ) ) { +\t\t\t\tcur = cur.parentNode; +\t\t\t} +\t\t\tfor ( ; cur; cur = cur.parentNode ) { +\t\t\t\teventPath.push( cur ); +\t\t\t\ttmp = cur; +\t\t\t} + +\t\t\t// Only add window if we got to document (e.g., not plain obj or detached DOM) +\t\t\tif ( tmp === (elem.ownerDocument || document) ) { +\t\t\t\teventPath.push( tmp.defaultView || tmp.parentWindow || window ); +\t\t\t} +\t\t} + +\t\t// Fire handlers on the event path +\t\ti = 0; +\t\twhile ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + +\t\t\tevent.type = i > 1 ? +\t\t\t\tbubbleType : +\t\t\t\tspecial.bindType || type; + +\t\t\t// jQuery handler +\t\t\thandle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); +\t\t\tif ( handle ) { +\t\t\t\thandle.apply( cur, data ); +\t\t\t} + +\t\t\t// Native handler +\t\t\thandle = ontype && cur[ ontype ]; +\t\t\tif ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { +\t\t\t\tevent.preventDefault(); +\t\t\t} +\t\t} +\t\tevent.type = type; + +\t\t// If nobody prevented the default action, do it now +\t\tif ( !onlyHandlers && !event.isDefaultPrevented() ) { + +\t\t\tif ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && +\t\t\t\t!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + +\t\t\t\t// Call a native DOM method on the target with the same name name as the event. +\t\t\t\t// Can't use an .isFunction() check here because IE6/7 fails that test. +\t\t\t\t// Don't do default actions on window, that's where global variables be (#6170) +\t\t\t\tif ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + +\t\t\t\t\t// Don't re-trigger an onFOO event when we call its FOO() method +\t\t\t\t\ttmp = elem[ ontype ]; + +\t\t\t\t\tif ( tmp ) { +\t\t\t\t\t\telem[ ontype ] = null; +\t\t\t\t\t} + +\t\t\t\t\t// Prevent re-triggering of the same event, since we already bubbled it above +\t\t\t\t\tjQuery.event.triggered = type; +\t\t\t\t\ttry { +\t\t\t\t\t\telem[ type ](); +\t\t\t\t\t} catch ( e ) { +\t\t\t\t\t\t// IE<9 dies on focus/blur to hidden element (#1486,#12518) +\t\t\t\t\t\t// only reproducible on winXP IE8 native, not IE9 in IE8 mode +\t\t\t\t\t} +\t\t\t\t\tjQuery.event.triggered = undefined; + +\t\t\t\t\tif ( tmp ) { +\t\t\t\t\t\telem[ ontype ] = tmp; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} + +\t\treturn event.result; +\t}, + +\tdispatch: function( event ) { + +\t\t// Make a writable jQuery.Event from the native event object +\t\tevent = jQuery.event.fix( event ); + +\t\tvar i, ret, handleObj, matched, j, +\t\t\thandlerQueue = [], +\t\t\targs = core_slice.call( arguments ), +\t\t\thandlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], +\t\t\tspecial = jQuery.event.special[ event.type ] || {}; + +\t\t// Use the fix-ed jQuery.Event rather than the (read-only) native event +\t\targs[0] = event; +\t\tevent.delegateTarget = this; + +\t\t// Call the preDispatch hook for the mapped type, and let it bail if desired +\t\tif ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { +\t\t\treturn; +\t\t} + +\t\t// Determine handlers +\t\thandlerQueue = jQuery.event.handlers.call( this, event, handlers ); + +\t\t// Run delegates first; they may want to stop propagation beneath us +\t\ti = 0; +\t\twhile ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { +\t\t\tevent.currentTarget = matched.elem; + +\t\t\tj = 0; +\t\t\twhile ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + +\t\t\t\t// Triggered event must either 1) have no namespace, or +\t\t\t\t// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). +\t\t\t\tif ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + +\t\t\t\t\tevent.handleObj = handleObj; +\t\t\t\t\tevent.data = handleObj.data; + +\t\t\t\t\tret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) +\t\t\t\t\t\t\t.apply( matched.elem, args ); + +\t\t\t\t\tif ( ret !== undefined ) { +\t\t\t\t\t\tif ( (event.result = ret) === false ) { +\t\t\t\t\t\t\tevent.preventDefault(); +\t\t\t\t\t\t\tevent.stopPropagation(); +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} + +\t\t// Call the postDispatch hook for the mapped type +\t\tif ( special.postDispatch ) { +\t\t\tspecial.postDispatch.call( this, event ); +\t\t} + +\t\treturn event.result; +\t}, + +\thandlers: function( event, handlers ) { +\t\tvar sel, handleObj, matches, i, +\t\t\thandlerQueue = [], +\t\t\tdelegateCount = handlers.delegateCount, +\t\t\tcur = event.target; + +\t\t// Find delegate handlers +\t\t// Black-hole SVG instance trees (#13180) +\t\t// Avoid non-left-click bubbling in Firefox (#3861) +\t\tif ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + +\t\t\tfor ( ; cur != this; cur = cur.parentNode || this ) { + +\t\t\t\t// Don't check non-elements (#13208) +\t\t\t\t// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) +\t\t\t\tif ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { +\t\t\t\t\tmatches = []; +\t\t\t\t\tfor ( i = 0; i < delegateCount; i++ ) { +\t\t\t\t\t\thandleObj = handlers[ i ]; + +\t\t\t\t\t\t// Don't conflict with Object.prototype properties (#13203) +\t\t\t\t\t\tsel = handleObj.selector + " "; + +\t\t\t\t\t\tif ( matches[ sel ] === undefined ) { +\t\t\t\t\t\t\tmatches[ sel ] = handleObj.needsContext ? +\t\t\t\t\t\t\t\tjQuery( sel, this ).index( cur ) >= 0 : +\t\t\t\t\t\t\t\tjQuery.find( sel, this, null, [ cur ] ).length; +\t\t\t\t\t\t} +\t\t\t\t\t\tif ( matches[ sel ] ) { +\t\t\t\t\t\t\tmatches.push( handleObj ); +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t\tif ( matches.length ) { +\t\t\t\t\t\thandlerQueue.push({ elem: cur, handlers: matches }); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} + +\t\t// Add the remaining (directly-bound) handlers +\t\tif ( delegateCount < handlers.length ) { +\t\t\thandlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); +\t\t} + +\t\treturn handlerQueue; +\t}, + +\tfix: function( event ) { +\t\tif ( event[ jQuery.expando ] ) { +\t\t\treturn event; +\t\t} + +\t\t// Create a writable copy of the event object and normalize some properties +\t\tvar i, prop, copy, +\t\t\ttype = event.type, +\t\t\toriginalEvent = event, +\t\t\tfixHook = this.fixHooks[ type ]; + +\t\tif ( !fixHook ) { +\t\t\tthis.fixHooks[ type ] = fixHook = +\t\t\t\trmouseEvent.test( type ) ? this.mouseHooks : +\t\t\t\trkeyEvent.test( type ) ? this.keyHooks : +\t\t\t\t{}; +\t\t} +\t\tcopy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + +\t\tevent = new jQuery.Event( originalEvent ); + +\t\ti = copy.length; +\t\twhile ( i-- ) { +\t\t\tprop = copy[ i ]; +\t\t\tevent[ prop ] = originalEvent[ prop ]; +\t\t} + +\t\t// Support: IE<9 +\t\t// Fix target property (#1925) +\t\tif ( !event.target ) { +\t\t\tevent.target = originalEvent.srcElement || document; +\t\t} + +\t\t// Support: Chrome 23+, Safari? +\t\t// Target should not be a text node (#504, #13143) +\t\tif ( event.target.nodeType === 3 ) { +\t\t\tevent.target = event.target.parentNode; +\t\t} + +\t\t// Support: IE<9 +\t\t// For mouse/key events, metaKey==false if it's undefined (#3368, #11328) +\t\tevent.metaKey = !!event.metaKey; + +\t\treturn fixHook.filter ? fixHook.filter( event, originalEvent ) : event; +\t}, + +\t// Includes some event props shared by KeyEvent and MouseEvent +\tprops: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + +\tfixHooks: {}, + +\tkeyHooks: { +\t\tprops: "char charCode key keyCode".split(" "), +\t\tfilter: function( event, original ) { + +\t\t\t// Add which for key events +\t\t\tif ( event.which == null ) { +\t\t\t\tevent.which = original.charCode != null ? original.charCode : original.keyCode; +\t\t\t} + +\t\t\treturn event; +\t\t} +\t}, + +\tmouseHooks: { +\t\tprops: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), +\t\tfilter: function( event, original ) { +\t\t\tvar body, eventDoc, doc, +\t\t\t\tbutton = original.button, +\t\t\t\tfromElement = original.fromElement; + +\t\t\t// Calculate pageX/Y if missing and clientX/Y available +\t\t\tif ( event.pageX == null && original.clientX != null ) { +\t\t\t\teventDoc = event.target.ownerDocument || document; +\t\t\t\tdoc = eventDoc.documentElement; +\t\t\t\tbody = eventDoc.body; + +\t\t\t\tevent.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); +\t\t\t\tevent.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); +\t\t\t} + +\t\t\t// Add relatedTarget, if necessary +\t\t\tif ( !event.relatedTarget && fromElement ) { +\t\t\t\tevent.relatedTarget = fromElement === event.target ? original.toElement : fromElement; +\t\t\t} + +\t\t\t// Add which for click: 1 === left; 2 === middle; 3 === right +\t\t\t// Note: button is not normalized, so don't use it +\t\t\tif ( !event.which && button !== undefined ) { +\t\t\t\tevent.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); +\t\t\t} + +\t\t\treturn event; +\t\t} +\t}, + +\tspecial: { +\t\tload: { +\t\t\t// Prevent triggered image.load events from bubbling to window.load +\t\t\tnoBubble: true +\t\t}, +\t\tclick: { +\t\t\t// For checkbox, fire native event so checked state will be right +\t\t\ttrigger: function() { +\t\t\t\tif ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { +\t\t\t\t\tthis.click(); +\t\t\t\t\treturn false; +\t\t\t\t} +\t\t\t} +\t\t}, +\t\tfocus: { +\t\t\t// Fire native event if possible so blur/focus sequence is correct +\t\t\ttrigger: function() { +\t\t\t\tif ( this !== document.activeElement && this.focus ) { +\t\t\t\t\ttry { +\t\t\t\t\t\tthis.focus(); +\t\t\t\t\t\treturn false; +\t\t\t\t\t} catch ( e ) { +\t\t\t\t\t\t// Support: IE<9 +\t\t\t\t\t\t// If we error on focus to hidden element (#1486, #12518), +\t\t\t\t\t\t// let .trigger() run the handlers +\t\t\t\t\t} +\t\t\t\t} +\t\t\t}, +\t\t\tdelegateType: "focusin" +\t\t}, +\t\tblur: { +\t\t\ttrigger: function() { +\t\t\t\tif ( this === document.activeElement && this.blur ) { +\t\t\t\t\tthis.blur(); +\t\t\t\t\treturn false; +\t\t\t\t} +\t\t\t}, +\t\t\tdelegateType: "focusout" +\t\t}, + +\t\tbeforeunload: { +\t\t\tpostDispatch: function( event ) { + +\t\t\t\t// Even when returnValue equals to undefined Firefox will still show alert +\t\t\t\tif ( event.result !== undefined ) { +\t\t\t\t\tevent.originalEvent.returnValue = event.result; +\t\t\t\t} +\t\t\t} +\t\t} +\t}, + +\tsimulate: function( type, elem, event, bubble ) { +\t\t// Piggyback on a donor event to simulate a different one. +\t\t// Fake originalEvent to avoid donor's stopPropagation, but if the +\t\t// simulated event prevents default then we do the same on the donor. +\t\tvar e = jQuery.extend( +\t\t\tnew jQuery.Event(), +\t\t\tevent, +\t\t\t{ type: type, +\t\t\t\tisSimulated: true, +\t\t\t\toriginalEvent: {} +\t\t\t} +\t\t); +\t\tif ( bubble ) { +\t\t\tjQuery.event.trigger( e, null, elem ); +\t\t} else { +\t\t\tjQuery.event.dispatch.call( elem, e ); +\t\t} +\t\tif ( e.isDefaultPrevented() ) { +\t\t\tevent.preventDefault(); +\t\t} +\t} }; jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - var name = "on" + type; - - if ( elem.detachEvent ) { - - // #8545, #7054, preventing memory leaks for custom events in IE6-8 - // detachEvent needed property on element, by name of that event, to properly expose it to GC - if ( typeof elem[ name ] === core_strundefined ) { - elem[ name ] = null; - } - - elem.detachEvent( name, handle ); - } - }; +\tfunction( elem, type, handle ) { +\t\tif ( elem.removeEventListener ) { +\t\t\telem.removeEventListener( type, handle, false ); +\t\t} +\t} : +\tfunction( elem, type, handle ) { +\t\tvar name = "on" + type; + +\t\tif ( elem.detachEvent ) { + +\t\t\t// #8545, #7054, preventing memory leaks for custom events in IE6-8 +\t\t\t// detachEvent needed property on element, by name of that event, to properly expose it to GC +\t\t\tif ( typeof elem[ name ] === core_strundefined ) { +\t\t\t\telem[ name ] = null; +\t\t\t} + +\t\t\telem.detachEvent( name, handle ); +\t\t} +\t}; jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; +\t// Allow instantiation without the 'new' keyword +\tif ( !(this instanceof jQuery.Event) ) { +\t\treturn new jQuery.Event( src, props ); +\t} + +\t// Event object +\tif ( src && src.type ) { +\t\tthis.originalEvent = src; +\t\tthis.type = src.type; + +\t\t// Events bubbling up the document may have been marked as prevented +\t\t// by a handler lower down the tree; reflect the correct value. +\t\tthis.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || +\t\t\tsrc.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + +\t// Event type +\t} else { +\t\tthis.type = src; +\t} + +\t// Put explicitly provided properties onto the event object +\tif ( props ) { +\t\tjQuery.extend( this, props ); +\t} + +\t// Create a timestamp if incoming event doesn't have one +\tthis.timeStamp = src && src.timeStamp || jQuery.now(); + +\t// Mark it as fixed +\tthis[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - if ( !e ) { - return; - } - - // If preventDefault exists, run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // Support: IE - // Otherwise set the returnValue property of the original event to false - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - if ( !e ) { - return; - } - // If stopPropagation exists, run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - - // Support: IE - // Set the cancelBubble property of the original event to true - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - } +\tisDefaultPrevented: returnFalse, +\tisPropagationStopped: returnFalse, +\tisImmediatePropagationStopped: returnFalse, + +\tpreventDefault: function() { +\t\tvar e = this.originalEvent; + +\t\tthis.isDefaultPrevented = returnTrue; +\t\tif ( !e ) { +\t\t\treturn; +\t\t} + +\t\t// If preventDefault exists, run it on the original event +\t\tif ( e.preventDefault ) { +\t\t\te.preventDefault(); + +\t\t// Support: IE +\t\t// Otherwise set the returnValue property of the original event to false +\t\t} else { +\t\t\te.returnValue = false; +\t\t} +\t}, +\tstopPropagation: function() { +\t\tvar e = this.originalEvent; + +\t\tthis.isPropagationStopped = returnTrue; +\t\tif ( !e ) { +\t\t\treturn; +\t\t} +\t\t// If stopPropagation exists, run it on the original event +\t\tif ( e.stopPropagation ) { +\t\t\te.stopPropagation(); +\t\t} + +\t\t// Support: IE +\t\t// Set the cancelBubble property of the original event to true +\t\te.cancelBubble = true; +\t}, +\tstopImmediatePropagation: function() { +\t\tthis.isImmediatePropagationStopped = returnTrue; +\t\tthis.stopPropagation(); +\t} }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" +\tmouseenter: "mouseover", +\tmouseleave: "mouseout" }, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; +\tjQuery.event.special[ orig ] = { +\t\tdelegateType: fix, +\t\tbindType: fix, + +\t\thandle: function( event ) { +\t\t\tvar ret, +\t\t\t\ttarget = this, +\t\t\t\trelated = event.relatedTarget, +\t\t\t\thandleObj = event.handleObj; + +\t\t\t// For mousenter/leave call the handler if related is outside the target. +\t\t\t// NB: No relatedTarget if the mouse left/entered the browser window +\t\t\tif ( !related || (related !== target && !jQuery.contains( target, related )) ) { +\t\t\t\tevent.type = handleObj.origType; +\t\t\t\tret = handleObj.handler.apply( this, arguments ); +\t\t\t\tevent.type = fix; +\t\t\t} +\t\t\treturn ret; +\t\t} +\t}; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !jQuery._data( form, "submitBubbles" ) ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - jQuery._data( form, "submitBubbles", true ); - } - }); - // return undefined since we don't need an event listener - }, - - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - } - }, - - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; +\tjQuery.event.special.submit = { +\t\tsetup: function() { +\t\t\t// Only need this for delegated form submit events +\t\t\tif ( jQuery.nodeName( this, "form" ) ) { +\t\t\t\treturn false; +\t\t\t} + +\t\t\t// Lazy-add a submit handler when a descendant form may potentially be submitted +\t\t\tjQuery.event.add( this, "click._submit keypress._submit", function( e ) { +\t\t\t\t// Node name check avoids a VML-related crash in IE (#9807) +\t\t\t\tvar elem = e.target, +\t\t\t\t\tform = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; +\t\t\t\tif ( form && !jQuery._data( form, "submitBubbles" ) ) { +\t\t\t\t\tjQuery.event.add( form, "submit._submit", function( event ) { +\t\t\t\t\t\tevent._submit_bubble = true; +\t\t\t\t\t}); +\t\t\t\t\tjQuery._data( form, "submitBubbles", true ); +\t\t\t\t} +\t\t\t}); +\t\t\t// return undefined since we don't need an event listener +\t\t}, + +\t\tpostDispatch: function( event ) { +\t\t\t// If form was submitted by the user, bubble the event up the tree +\t\t\tif ( event._submit_bubble ) { +\t\t\t\tdelete event._submit_bubble; +\t\t\t\tif ( this.parentNode && !event.isTrigger ) { +\t\t\t\t\tjQuery.event.simulate( "submit", this.parentNode, event, true ); +\t\t\t\t} +\t\t\t} +\t\t}, + +\t\tteardown: function() { +\t\t\t// Only need this for delegated form submit events +\t\t\tif ( jQuery.nodeName( this, "form" ) ) { +\t\t\t\treturn false; +\t\t\t} + +\t\t\t// Remove delegated handlers; cleanData eventually reaps submit handlers attached above +\t\t\tjQuery.event.remove( this, "._submit" ); +\t\t} +\t}; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { - jQuery.event.special.change = { - - setup: function() { - - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - } - // Allow triggered, simulated change events (#11500) - jQuery.event.simulate( "change", this, event, true ); - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - jQuery._data( elem, "changeBubbles", true ); - } - }); - }, - - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return !rformElems.test( this.nodeName ); - } - }; +\tjQuery.event.special.change = { + +\t\tsetup: function() { + +\t\t\tif ( rformElems.test( this.nodeName ) ) { +\t\t\t\t// IE doesn't fire change on a check/radio until blur; trigger it on click +\t\t\t\t// after a propertychange. Eat the blur-change in special.change.handle. +\t\t\t\t// This still fires onchange a second time for check/radio after blur. +\t\t\t\tif ( this.type === "checkbox" || this.type === "radio" ) { +\t\t\t\t\tjQuery.event.add( this, "propertychange._change", function( event ) { +\t\t\t\t\t\tif ( event.originalEvent.propertyName === "checked" ) { +\t\t\t\t\t\t\tthis._just_changed = true; +\t\t\t\t\t\t} +\t\t\t\t\t}); +\t\t\t\t\tjQuery.event.add( this, "click._change", function( event ) { +\t\t\t\t\t\tif ( this._just_changed && !event.isTrigger ) { +\t\t\t\t\t\t\tthis._just_changed = false; +\t\t\t\t\t\t} +\t\t\t\t\t\t// Allow triggered, simulated change events (#11500) +\t\t\t\t\t\tjQuery.event.simulate( "change", this, event, true ); +\t\t\t\t\t}); +\t\t\t\t} +\t\t\t\treturn false; +\t\t\t} +\t\t\t// Delegated event; lazy-add a change handler on descendant inputs +\t\t\tjQuery.event.add( this, "beforeactivate._change", function( e ) { +\t\t\t\tvar elem = e.target; + +\t\t\t\tif ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { +\t\t\t\t\tjQuery.event.add( elem, "change._change", function( event ) { +\t\t\t\t\t\tif ( this.parentNode && !event.isSimulated && !event.isTrigger ) { +\t\t\t\t\t\t\tjQuery.event.simulate( "change", this.parentNode, event, true ); +\t\t\t\t\t\t} +\t\t\t\t\t}); +\t\t\t\t\tjQuery._data( elem, "changeBubbles", true ); +\t\t\t\t} +\t\t\t}); +\t\t}, + +\t\thandle: function( event ) { +\t\t\tvar elem = event.target; + +\t\t\t// Swallow native change events from checkbox/radio, we already triggered them above +\t\t\tif ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { +\t\t\t\treturn event.handleObj.handler.apply( this, arguments ); +\t\t\t} +\t\t}, + +\t\tteardown: function() { +\t\t\tjQuery.event.remove( this, "._change" ); + +\t\t\treturn !rformElems.test( this.nodeName ); +\t\t} +\t}; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - }); +\tjQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + +\t\t// Attach a single capturing handler while someone wants focusin/focusout +\t\tvar attaches = 0, +\t\t\thandler = function( event ) { +\t\t\t\tjQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); +\t\t\t}; + +\t\tjQuery.event.special[ fix ] = { +\t\t\tsetup: function() { +\t\t\t\tif ( attaches++ === 0 ) { +\t\t\t\t\tdocument.addEventListener( orig, handler, true ); +\t\t\t\t} +\t\t\t}, +\t\t\tteardown: function() { +\t\t\t\tif ( --attaches === 0 ) { +\t\t\t\t\tdocument.removeEventListener( orig, handler, true ); +\t\t\t\t} +\t\t\t} +\t\t}; +\t}); } jQuery.fn.extend({ - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var type, origFn; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - var elem = this[0]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } +\ton: function( types, selector, data, fn, /*INTERNAL*/ one ) { +\t\tvar type, origFn; + +\t\t// Types can be a map of types/handlers +\t\tif ( typeof types === "object" ) { +\t\t\t// ( types-Object, selector, data ) +\t\t\tif ( typeof selector !== "string" ) { +\t\t\t\t// ( types-Object, data ) +\t\t\t\tdata = data || selector; +\t\t\t\tselector = undefined; +\t\t\t} +\t\t\tfor ( type in types ) { +\t\t\t\tthis.on( type, selector, data, types[ type ], one ); +\t\t\t} +\t\t\treturn this; +\t\t} + +\t\tif ( data == null && fn == null ) { +\t\t\t// ( types, fn ) +\t\t\tfn = selector; +\t\t\tdata = selector = undefined; +\t\t} else if ( fn == null ) { +\t\t\tif ( typeof selector === "string" ) { +\t\t\t\t// ( types, selector, fn ) +\t\t\t\tfn = data; +\t\t\t\tdata = undefined; +\t\t\t} else { +\t\t\t\t// ( types, data, fn ) +\t\t\t\tfn = data; +\t\t\t\tdata = selector; +\t\t\t\tselector = undefined; +\t\t\t} +\t\t} +\t\tif ( fn === false ) { +\t\t\tfn = returnFalse; +\t\t} else if ( !fn ) { +\t\t\treturn this; +\t\t} + +\t\tif ( one === 1 ) { +\t\t\torigFn = fn; +\t\t\tfn = function( event ) { +\t\t\t\t// Can use an empty set, since event contains the info +\t\t\t\tjQuery().off( event ); +\t\t\t\treturn origFn.apply( this, arguments ); +\t\t\t}; +\t\t\t// Use same guid so caller can remove using origFn +\t\t\tfn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); +\t\t} +\t\treturn this.each( function() { +\t\t\tjQuery.event.add( this, types, fn, data, selector ); +\t\t}); +\t}, +\tone: function( types, selector, data, fn ) { +\t\treturn this.on( types, selector, data, fn, 1 ); +\t}, +\toff: function( types, selector, fn ) { +\t\tvar handleObj, type; +\t\tif ( types && types.preventDefault && types.handleObj ) { +\t\t\t// ( event ) dispatched jQuery.Event +\t\t\thandleObj = types.handleObj; +\t\t\tjQuery( types.delegateTarget ).off( +\t\t\t\thandleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, +\t\t\t\thandleObj.selector, +\t\t\t\thandleObj.handler +\t\t\t); +\t\t\treturn this; +\t\t} +\t\tif ( typeof types === "object" ) { +\t\t\t// ( types-object [, selector] ) +\t\t\tfor ( type in types ) { +\t\t\t\tthis.off( type, selector, types[ type ] ); +\t\t\t} +\t\t\treturn this; +\t\t} +\t\tif ( selector === false || typeof selector === "function" ) { +\t\t\t// ( types [, fn] ) +\t\t\tfn = selector; +\t\t\tselector = undefined; +\t\t} +\t\tif ( fn === false ) { +\t\t\tfn = returnFalse; +\t\t} +\t\treturn this.each(function() { +\t\t\tjQuery.event.remove( this, types, fn, selector ); +\t\t}); +\t}, + +\tbind: function( types, data, fn ) { +\t\treturn this.on( types, null, data, fn ); +\t}, +\tunbind: function( types, fn ) { +\t\treturn this.off( types, null, fn ); +\t}, + +\tdelegate: function( selector, types, data, fn ) { +\t\treturn this.on( types, selector, data, fn ); +\t}, +\tundelegate: function( selector, types, fn ) { +\t\t// ( namespace ) or ( selector, types [, fn] ) +\t\treturn arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); +\t}, + +\ttrigger: function( type, data ) { +\t\treturn this.each(function() { +\t\t\tjQuery.event.trigger( type, data, this ); +\t\t}); +\t}, +\ttriggerHandler: function( type, data ) { +\t\tvar elem = this[0]; +\t\tif ( elem ) { +\t\t\treturn jQuery.event.trigger( type, data, elem, true ); +\t\t} +\t} }); /*! * Sizzle CSS Selector Engine @@ -3693,145 +3693,145 @@ jQuery.fn.extend({ (function( window, undefined ) { var i, - cachedruns, - Expr, - getText, - isXML, - compile, - hasDuplicate, - outermostContext, - - // Local document vars - setDocument, - document, - docElem, - documentIsXML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - sortOrder, - - // Instance-specific data - expando = "sizzle" + -(new Date()), - preferredDoc = window.document, - support = {}, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - - // General-purpose constants - strundefined = typeof undefined, - MAX_NEGATIVE = 1 << 31, - - // Array methods - arr = [], - pop = arr.pop, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf if we can't use a native one - indexOf = arr.indexOf || function( elem ) { - var i = 0, - len = this.length; - for ( ; i < len; i++ ) { - if ( this[i] === elem ) { - return i; - } - } - return -1; - }, - - - // Regular expressions - - // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/css3-syntax/#characters - characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - - // Loosely modeled on CSS identifier characters - // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors - // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = characterEncoding.replace( "w", "w#" ), - - // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors - operators = "([*^$|!~]?=)", - attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + - "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", - - // Prefer arguments quoted, - // then not containing pseudos/brackets, - // then attribute selectors/non-parenthetical expressions, - // then anything else - // These preferences are here to reduce the number of selectors - // needing tokenize in the PSEUDO preFilter - pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + characterEncoding + ")" ), - "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), - "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rsibling = /[\x20\t\r\n\f]*[+~]/, - - rnative = /^[^{]+\{\s*\[native code/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rescape = /'|\\/g, - rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, - - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, - funescape = function( _, escaped ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - return high !== high ? - escaped : - // BMP codepoint - high < 0 ? - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }; +\tcachedruns, +\tExpr, +\tgetText, +\tisXML, +\tcompile, +\thasDuplicate, +\toutermostContext, + +\t// Local document vars +\tsetDocument, +\tdocument, +\tdocElem, +\tdocumentIsXML, +\trbuggyQSA, +\trbuggyMatches, +\tmatches, +\tcontains, +\tsortOrder, + +\t// Instance-specific data +\texpando = "sizzle" + -(new Date()), +\tpreferredDoc = window.document, +\tsupport = {}, +\tdirruns = 0, +\tdone = 0, +\tclassCache = createCache(), +\ttokenCache = createCache(), +\tcompilerCache = createCache(), + +\t// General-purpose constants +\tstrundefined = typeof undefined, +\tMAX_NEGATIVE = 1 << 31, + +\t// Array methods +\tarr = [], +\tpop = arr.pop, +\tpush = arr.push, +\tslice = arr.slice, +\t// Use a stripped-down indexOf if we can't use a native one +\tindexOf = arr.indexOf || function( elem ) { +\t\tvar i = 0, +\t\t\tlen = this.length; +\t\tfor ( ; i < len; i++ ) { +\t\t\tif ( this[i] === elem ) { +\t\t\t\treturn i; +\t\t\t} +\t\t} +\t\treturn -1; +\t}, + + +\t// Regular expressions + +\t// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace +\twhitespace = "[\\x20\\t\\r\\n\\f]", +\t// http://www.w3.org/TR/css3-syntax/#characters +\tcharacterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + +\t// Loosely modeled on CSS identifier characters +\t// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors +\t// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier +\tidentifier = characterEncoding.replace( "w", "w#" ), + +\t// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors +\toperators = "([*^$|!~]?=)", +\tattributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + +\t\t"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + +\t// Prefer arguments quoted, +\t// then not containing pseudos/brackets, +\t// then attribute selectors/non-parenthetical expressions, +\t// then anything else +\t// These preferences are here to reduce the number of selectors +\t// needing tokenize in the PSEUDO preFilter +\tpseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + +\t// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter +\trtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + +\trcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), +\trcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), +\trpseudo = new RegExp( pseudos ), +\tridentifier = new RegExp( "^" + identifier + "$" ), + +\tmatchExpr = { +\t\t"ID": new RegExp( "^#(" + characterEncoding + ")" ), +\t\t"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), +\t\t"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), +\t\t"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), +\t\t"ATTR": new RegExp( "^" + attributes ), +\t\t"PSEUDO": new RegExp( "^" + pseudos ), +\t\t"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + +\t\t\t"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + +\t\t\t"*(\\d+)|))" + whitespace + "*\\)|)", "i" ), +\t\t// For use in libraries implementing .is() +\t\t// We use this for POS matching in `select` +\t\t"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + +\t\t\twhitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) +\t}, + +\trsibling = /[\x20\t\r\n\f]*[+~]/, + +\trnative = /^[^{]+\{\s*\[native code/, + +\t// Easily-parseable/retrievable ID or TAG or CLASS selectors +\trquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + +\trinputs = /^(?:input|select|textarea|button)$/i, +\trheader = /^h\d$/i, + +\trescape = /'|\\/g, +\trattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + +\t// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters +\trunescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, +\tfunescape = function( _, escaped ) { +\t\tvar high = "0x" + escaped - 0x10000; +\t\t// NaN means non-codepoint +\t\treturn high !== high ? +\t\t\tescaped : +\t\t\t// BMP codepoint +\t\t\thigh < 0 ? +\t\t\t\tString.fromCharCode( high + 0x10000 ) : +\t\t\t\t// Supplemental Plane codepoint (surrogate pair) +\t\t\t\tString.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); +\t}; // Use a stripped-down slice if we can't use a native one try { - slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; +\tslice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { - slice = function( i ) { - var elem, - results = []; - while ( (elem = this[i++]) ) { - results.push( elem ); - } - return results; - }; +\tslice = function( i ) { +\t\tvar elem, +\t\t\tresults = []; +\t\twhile ( (elem = this[i++]) ) { +\t\t\tresults.push( elem ); +\t\t} +\t\treturn results; +\t}; } /** @@ -3839,27 +3839,27 @@ try { * @param {Function} fn The function to test for native support */ function isNative( fn ) { - return rnative.test( fn + "" ); +\treturn rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry + *\tproperty name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + *\tdeleting the oldest entry */ function createCache() { - var cache, - keys = []; - - return (cache = function( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key += " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key ] = value); - }); +\tvar cache, +\t\tkeys = []; + +\treturn (cache = function( key, value ) { +\t\t// Use (key + " ") to avoid collision with native prototype properties (see Issue #157) +\t\tif ( keys.push( key += " " ) > Expr.cacheLength ) { +\t\t\t// Only keep the most recent entries +\t\t\tdelete cache[ keys.shift() ]; +\t\t} +\t\treturn (cache[ key ] = value); +\t}); } /** @@ -3867,8 +3867,8 @@ function createCache() { * @param {Function} fn The function to mark */ function markFunction( fn ) { - fn[ expando ] = true; - return fn; +\tfn[ expando ] = true; +\treturn fn; } /** @@ -3876,126 +3876,126 @@ function markFunction( fn ) { * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { - var div = document.createElement("div"); - - try { - return fn( div ); - } catch (e) { - return false; - } finally { - // release memory in IE - div = null; - } +\tvar div = document.createElement("div"); + +\ttry { +\t\treturn fn( div ); +\t} catch (e) { +\t\treturn false; +\t} finally { +\t\t// release memory in IE +\t\tdiv = null; +\t} } function Sizzle( selector, context, results, seed ) { - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; - - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } - - context = context || document; - results = results || []; - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { - return []; - } - - if ( !documentIsXML && !seed ) { - - // Shortcuts - if ( (match = rquickExpr.exec( selector )) ) { - // Speed-up: Sizzle("#ID") - if ( (m = match[1]) ) { - if ( nodeType === 9 ) { - elem = context.getElementById( m ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - } else { - // Context is not a document - if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && - contains( context, elem ) && elem.id === m ) { - results.push( elem ); - return results; - } - } - - // Speed-up: Sizzle("TAG") - } else if ( match[2] ) { - push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); - return results; - - // Speed-up: Sizzle(".CLASS") - } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { - push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); - return results; - } - } - - // QSA path - if ( support.qsa && !rbuggyQSA.test(selector) ) { - old = true; - nid = expando; - newContext = context; - newSelector = nodeType === 9 && selector; - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - groups = tokenize( selector ); - - if ( (old = context.getAttribute("id")) ) { - nid = old.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", nid ); - } - nid = "[id='" + nid + "'] "; - - i = groups.length; - while ( i-- ) { - groups[i] = nid + toSelector( groups[i] ); - } - newContext = rsibling.test( selector ) && context.parentNode || context; - newSelector = groups.join(","); - } - - if ( newSelector ) { - try { - push.apply( results, slice.call( newContext.querySelectorAll( - newSelector - ), 0 ) ); - return results; - } catch(qsaError) { - } finally { - if ( !old ) { - context.removeAttribute("id"); - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); +\tvar match, elem, m, nodeType, +\t\t// QSA vars +\t\ti, groups, old, nid, newContext, newSelector; + +\tif ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { +\t\tsetDocument( context ); +\t} + +\tcontext = context || document; +\tresults = results || []; + +\tif ( !selector || typeof selector !== "string" ) { +\t\treturn results; +\t} + +\tif ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { +\t\treturn []; +\t} + +\tif ( !documentIsXML && !seed ) { + +\t\t// Shortcuts +\t\tif ( (match = rquickExpr.exec( selector )) ) { +\t\t\t// Speed-up: Sizzle("#ID") +\t\t\tif ( (m = match[1]) ) { +\t\t\t\tif ( nodeType === 9 ) { +\t\t\t\t\telem = context.getElementById( m ); +\t\t\t\t\t// Check parentNode to catch when Blackberry 4.6 returns +\t\t\t\t\t// nodes that are no longer in the document #6963 +\t\t\t\t\tif ( elem && elem.parentNode ) { +\t\t\t\t\t\t// Handle the case where IE, Opera, and Webkit return items +\t\t\t\t\t\t// by name instead of ID +\t\t\t\t\t\tif ( elem.id === m ) { +\t\t\t\t\t\t\tresults.push( elem ); +\t\t\t\t\t\t\treturn results; +\t\t\t\t\t\t} +\t\t\t\t\t} else { +\t\t\t\t\t\treturn results; +\t\t\t\t\t} +\t\t\t\t} else { +\t\t\t\t\t// Context is not a document +\t\t\t\t\tif ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && +\t\t\t\t\t\tcontains( context, elem ) && elem.id === m ) { +\t\t\t\t\t\tresults.push( elem ); +\t\t\t\t\t\treturn results; +\t\t\t\t\t} +\t\t\t\t} + +\t\t\t// Speed-up: Sizzle("TAG") +\t\t\t} else if ( match[2] ) { +\t\t\t\tpush.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); +\t\t\t\treturn results; + +\t\t\t// Speed-up: Sizzle(".CLASS") +\t\t\t} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { +\t\t\t\tpush.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); +\t\t\t\treturn results; +\t\t\t} +\t\t} + +\t\t// QSA path +\t\tif ( support.qsa && !rbuggyQSA.test(selector) ) { +\t\t\told = true; +\t\t\tnid = expando; +\t\t\tnewContext = context; +\t\t\tnewSelector = nodeType === 9 && selector; + +\t\t\t// qSA works strangely on Element-rooted queries +\t\t\t// We can work around this by specifying an extra ID on the root +\t\t\t// and working up from there (Thanks to Andrew Dupont for the technique) +\t\t\t// IE 8 doesn't work on object elements +\t\t\tif ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { +\t\t\t\tgroups = tokenize( selector ); + +\t\t\t\tif ( (old = context.getAttribute("id")) ) { +\t\t\t\t\tnid = old.replace( rescape, "\\$&" ); +\t\t\t\t} else { +\t\t\t\t\tcontext.setAttribute( "id", nid ); +\t\t\t\t} +\t\t\t\tnid = "[id='" + nid + "'] "; + +\t\t\t\ti = groups.length; +\t\t\t\twhile ( i-- ) { +\t\t\t\t\tgroups[i] = nid + toSelector( groups[i] ); +\t\t\t\t} +\t\t\t\tnewContext = rsibling.test( selector ) && context.parentNode || context; +\t\t\t\tnewSelector = groups.join(","); +\t\t\t} + +\t\t\tif ( newSelector ) { +\t\t\t\ttry { +\t\t\t\t\tpush.apply( results, slice.call( newContext.querySelectorAll( +\t\t\t\t\t\tnewSelector +\t\t\t\t\t), 0 ) ); +\t\t\t\t\treturn results; +\t\t\t\t} catch(qsaError) { +\t\t\t\t} finally { +\t\t\t\t\tif ( !old ) { +\t\t\t\t\t\tcontext.removeAttribute("id"); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} +\t} + +\t// All others +\treturn select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** @@ -4003,10 +4003,10 @@ function Sizzle( selector, context, results, seed ) { * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; +\t// documentElement is verified for cases where it doesn't yet exist +\t// (such as loading iframes in IE - #4833) +\tvar documentElement = elem && (elem.ownerDocument || elem).documentElement; +\treturn documentElement ? documentElement.nodeName !== "HTML" : false; }; /** @@ -4015,491 +4015,491 @@ isXML = Sizzle.isXML = function( elem ) { * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { - var doc = node ? node.ownerDocument || node : preferredDoc; - - // If no document and documentElement is available, return - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Set our document - document = doc; - docElem = doc.documentElement; - - // Support tests - documentIsXML = isXML( doc ); - - // Check if getElementsByTagName("*") returns only elements - support.tagNameNoComments = assert(function( div ) { - div.appendChild( doc.createComment("") ); - return !div.getElementsByTagName("*").length; - }); - - // Check if attributes should be retrieved by attribute nodes - support.attributes = assert(function( div ) { - div.innerHTML = ""; - var type = typeof div.lastChild.getAttribute("multiple"); - // IE8 returns a string for some attributes even when not present - return type !== "boolean" && type !== "string"; - }); - - // Check if getElementsByClassName can be trusted - support.getByClassName = assert(function( div ) { - // Opera can't find a second classname (in 9.6) - div.innerHTML = ""; - if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { - return false; - } - - // Safari 3.2 caches class attributes and doesn't catch changes - div.lastChild.className = "e"; - return div.getElementsByClassName("e").length === 2; - }); - - // Check if getElementById returns elements by name - // Check if getElementsByName privileges form controls or returns elements by ID - support.getByName = assert(function( div ) { - // Inject content - div.id = expando + 0; - div.innerHTML = "
          "; - docElem.insertBefore( div, docElem.firstChild ); - - // Test - var pass = doc.getElementsByName && - // buggy browsers will return fewer than the correct 2 - doc.getElementsByName( expando ).length === 2 + - // buggy browsers will return more than the correct 0 - doc.getElementsByName( expando + 0 ).length; - support.getIdNotName = !doc.getElementById( expando ); - - // Cleanup - docElem.removeChild( div ); - - return pass; - }); - - // IE6/7 return modified attributes - Expr.attrHandle = assert(function( div ) { - div.innerHTML = ""; - return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && - div.firstChild.getAttribute("href") === "#"; - }) ? - {} : - { - "href": function( elem ) { - return elem.getAttribute( "href", 2 ); - }, - "type": function( elem ) { - return elem.getAttribute("type"); - } - }; - - // ID find and filter - if ( support.getIdNotName ) { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && !documentIsXML ) { - var m = context.getElementById( id ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - } else { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && !documentIsXML ) { - var m = context.getElementById( id ); - - return m ? - m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? - [m] : - undefined : - []; - } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - } - - // Tag - Expr.find["TAG"] = support.tagNameNoComments ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== strundefined ) { - return context.getElementsByTagName( tag ); - } - } : - function( tag, context ) { - var elem, - tmp = [], - i = 0, - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Name - Expr.find["NAME"] = support.getByName && function( tag, context ) { - if ( typeof context.getElementsByName !== strundefined ) { - return context.getElementsByName( name ); - } - }; - - // Class - Expr.find["CLASS"] = support.getByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { - return context.getElementsByClassName( className ); - } - }; - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21), - // no need to also add to buggyMatches since matches checks buggyQSA - // A support test would require too much code (would include document ready) - rbuggyQSA = [ ":focus" ]; - - if ( (support.qsa = isNative(doc.querySelectorAll)) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( div ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explictly - // setting a boolean content attribute, - // since its presence should be enough - // http://bugs.jquery.com/ticket/12359 - div.innerHTML = ""; - - // IE8 - Some boolean attributes are not treated correctly - if ( !div.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); - } - }); - - assert(function( div ) { - - // Opera 10-12/IE8 - ^= $= *= and empty values - // Should not select anything - div.innerHTML = ""; - if ( div.querySelectorAll("[i^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":enabled").length ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Opera 10-11 does not throw on post-comma invalid pseudos - div.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || - docElem.mozMatchesSelector || - docElem.webkitMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( div ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( div, "div" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( div, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } - - rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); - - // Element contains another - // Purposefully does not implement inclusive descendent - // As in, an element does not contain itself - contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - // Document order sorting - sortOrder = docElem.compareDocumentPosition ? - function( a, b ) { - var compare; - - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { - if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { - if ( a === doc || contains( preferredDoc, a ) ) { - return -1; - } - if ( b === doc || contains( preferredDoc, b ) ) { - return 1; - } - return 0; - } - return compare & 4 ? -1 : 1; - } - - return a.compareDocumentPosition ? -1 : 1; - } : - function( a, b ) { - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Parentless nodes are either documents or disconnected - } else if ( !aup || !bup ) { - return a === doc ? -1 : - b === doc ? 1 : - aup ? -1 : - bup ? 1 : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } - - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : - - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; - - // Always assume the presence of duplicates if sort doesn't - // pass them to our comparison function (as in Google Chrome). - hasDuplicate = false; - [0, 0].sort( sortOrder ); - support.detectDuplicates = hasDuplicate; - - return document; +\tvar doc = node ? node.ownerDocument || node : preferredDoc; + +\t// If no document and documentElement is available, return +\tif ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { +\t\treturn document; +\t} + +\t// Set our document +\tdocument = doc; +\tdocElem = doc.documentElement; + +\t// Support tests +\tdocumentIsXML = isXML( doc ); + +\t// Check if getElementsByTagName("*") returns only elements +\tsupport.tagNameNoComments = assert(function( div ) { +\t\tdiv.appendChild( doc.createComment("") ); +\t\treturn !div.getElementsByTagName("*").length; +\t}); + +\t// Check if attributes should be retrieved by attribute nodes +\tsupport.attributes = assert(function( div ) { +\t\tdiv.innerHTML = ""; +\t\tvar type = typeof div.lastChild.getAttribute("multiple"); +\t\t// IE8 returns a string for some attributes even when not present +\t\treturn type !== "boolean" && type !== "string"; +\t}); + +\t// Check if getElementsByClassName can be trusted +\tsupport.getByClassName = assert(function( div ) { +\t\t// Opera can't find a second classname (in 9.6) +\t\tdiv.innerHTML = ""; +\t\tif ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { +\t\t\treturn false; +\t\t} + +\t\t// Safari 3.2 caches class attributes and doesn't catch changes +\t\tdiv.lastChild.className = "e"; +\t\treturn div.getElementsByClassName("e").length === 2; +\t}); + +\t// Check if getElementById returns elements by name +\t// Check if getElementsByName privileges form controls or returns elements by ID +\tsupport.getByName = assert(function( div ) { +\t\t// Inject content +\t\tdiv.id = expando + 0; +\t\tdiv.innerHTML = "
          "; +\t\tdocElem.insertBefore( div, docElem.firstChild ); + +\t\t// Test +\t\tvar pass = doc.getElementsByName && +\t\t\t// buggy browsers will return fewer than the correct 2 +\t\t\tdoc.getElementsByName( expando ).length === 2 + +\t\t\t// buggy browsers will return more than the correct 0 +\t\t\tdoc.getElementsByName( expando + 0 ).length; +\t\tsupport.getIdNotName = !doc.getElementById( expando ); + +\t\t// Cleanup +\t\tdocElem.removeChild( div ); + +\t\treturn pass; +\t}); + +\t// IE6/7 return modified attributes +\tExpr.attrHandle = assert(function( div ) { +\t\tdiv.innerHTML = ""; +\t\treturn div.firstChild && typeof div.firstChild.getAttribute !== strundefined && +\t\t\tdiv.firstChild.getAttribute("href") === "#"; +\t}) ? +\t\t{} : +\t\t{ +\t\t\t"href": function( elem ) { +\t\t\t\treturn elem.getAttribute( "href", 2 ); +\t\t\t}, +\t\t\t"type": function( elem ) { +\t\t\t\treturn elem.getAttribute("type"); +\t\t\t} +\t\t}; + +\t// ID find and filter +\tif ( support.getIdNotName ) { +\t\tExpr.find["ID"] = function( id, context ) { +\t\t\tif ( typeof context.getElementById !== strundefined && !documentIsXML ) { +\t\t\t\tvar m = context.getElementById( id ); +\t\t\t\t// Check parentNode to catch when Blackberry 4.6 returns +\t\t\t\t// nodes that are no longer in the document #6963 +\t\t\t\treturn m && m.parentNode ? [m] : []; +\t\t\t} +\t\t}; +\t\tExpr.filter["ID"] = function( id ) { +\t\t\tvar attrId = id.replace( runescape, funescape ); +\t\t\treturn function( elem ) { +\t\t\t\treturn elem.getAttribute("id") === attrId; +\t\t\t}; +\t\t}; +\t} else { +\t\tExpr.find["ID"] = function( id, context ) { +\t\t\tif ( typeof context.getElementById !== strundefined && !documentIsXML ) { +\t\t\t\tvar m = context.getElementById( id ); + +\t\t\t\treturn m ? +\t\t\t\t\tm.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? +\t\t\t\t\t\t[m] : +\t\t\t\t\t\tundefined : +\t\t\t\t\t[]; +\t\t\t} +\t\t}; +\t\tExpr.filter["ID"] = function( id ) { +\t\t\tvar attrId = id.replace( runescape, funescape ); +\t\t\treturn function( elem ) { +\t\t\t\tvar node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); +\t\t\t\treturn node && node.value === attrId; +\t\t\t}; +\t\t}; +\t} + +\t// Tag +\tExpr.find["TAG"] = support.tagNameNoComments ? +\t\tfunction( tag, context ) { +\t\t\tif ( typeof context.getElementsByTagName !== strundefined ) { +\t\t\t\treturn context.getElementsByTagName( tag ); +\t\t\t} +\t\t} : +\t\tfunction( tag, context ) { +\t\t\tvar elem, +\t\t\t\ttmp = [], +\t\t\t\ti = 0, +\t\t\t\tresults = context.getElementsByTagName( tag ); + +\t\t\t// Filter out possible comments +\t\t\tif ( tag === "*" ) { +\t\t\t\twhile ( (elem = results[i++]) ) { +\t\t\t\t\tif ( elem.nodeType === 1 ) { +\t\t\t\t\t\ttmp.push( elem ); +\t\t\t\t\t} +\t\t\t\t} + +\t\t\t\treturn tmp; +\t\t\t} +\t\t\treturn results; +\t\t}; + +\t// Name +\tExpr.find["NAME"] = support.getByName && function( tag, context ) { +\t\tif ( typeof context.getElementsByName !== strundefined ) { +\t\t\treturn context.getElementsByName( name ); +\t\t} +\t}; + +\t// Class +\tExpr.find["CLASS"] = support.getByClassName && function( className, context ) { +\t\tif ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { +\t\t\treturn context.getElementsByClassName( className ); +\t\t} +\t}; + +\t// QSA and matchesSelector support + +\t// matchesSelector(:active) reports false when true (IE9/Opera 11.5) +\trbuggyMatches = []; + +\t// qSa(:focus) reports false when true (Chrome 21), +\t// no need to also add to buggyMatches since matches checks buggyQSA +\t// A support test would require too much code (would include document ready) +\trbuggyQSA = [ ":focus" ]; + +\tif ( (support.qsa = isNative(doc.querySelectorAll)) ) { +\t\t// Build QSA regex +\t\t// Regex strategy adopted from Diego Perini +\t\tassert(function( div ) { +\t\t\t// Select is set to empty string on purpose +\t\t\t// This is to test IE's treatment of not explictly +\t\t\t// setting a boolean content attribute, +\t\t\t// since its presence should be enough +\t\t\t// http://bugs.jquery.com/ticket/12359 +\t\t\tdiv.innerHTML = ""; + +\t\t\t// IE8 - Some boolean attributes are not treated correctly +\t\t\tif ( !div.querySelectorAll("[selected]").length ) { +\t\t\t\trbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); +\t\t\t} + +\t\t\t// Webkit/Opera - :checked should return selected option elements +\t\t\t// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked +\t\t\t// IE8 throws error here and will not see later tests +\t\t\tif ( !div.querySelectorAll(":checked").length ) { +\t\t\t\trbuggyQSA.push(":checked"); +\t\t\t} +\t\t}); + +\t\tassert(function( div ) { + +\t\t\t// Opera 10-12/IE8 - ^= $= *= and empty values +\t\t\t// Should not select anything +\t\t\tdiv.innerHTML = ""; +\t\t\tif ( div.querySelectorAll("[i^='']").length ) { +\t\t\t\trbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); +\t\t\t} + +\t\t\t// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) +\t\t\t// IE8 throws error here and will not see later tests +\t\t\tif ( !div.querySelectorAll(":enabled").length ) { +\t\t\t\trbuggyQSA.push( ":enabled", ":disabled" ); +\t\t\t} + +\t\t\t// Opera 10-11 does not throw on post-comma invalid pseudos +\t\t\tdiv.querySelectorAll("*,:x"); +\t\t\trbuggyQSA.push(",.*:"); +\t\t}); +\t} + +\tif ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || +\t\tdocElem.mozMatchesSelector || +\t\tdocElem.webkitMatchesSelector || +\t\tdocElem.oMatchesSelector || +\t\tdocElem.msMatchesSelector) )) ) { + +\t\tassert(function( div ) { +\t\t\t// Check to see if it's possible to do matchesSelector +\t\t\t// on a disconnected node (IE 9) +\t\t\tsupport.disconnectedMatch = matches.call( div, "div" ); + +\t\t\t// This should fail with an exception +\t\t\t// Gecko does not error, returns false instead +\t\t\tmatches.call( div, "[s!='']:x" ); +\t\t\trbuggyMatches.push( "!=", pseudos ); +\t\t}); +\t} + +\trbuggyQSA = new RegExp( rbuggyQSA.join("|") ); +\trbuggyMatches = new RegExp( rbuggyMatches.join("|") ); + +\t// Element contains another +\t// Purposefully does not implement inclusive descendent +\t// As in, an element does not contain itself +\tcontains = isNative(docElem.contains) || docElem.compareDocumentPosition ? +\t\tfunction( a, b ) { +\t\t\tvar adown = a.nodeType === 9 ? a.documentElement : a, +\t\t\t\tbup = b && b.parentNode; +\t\t\treturn a === bup || !!( bup && bup.nodeType === 1 && ( +\t\t\t\tadown.contains ? +\t\t\t\t\tadown.contains( bup ) : +\t\t\t\t\ta.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 +\t\t\t)); +\t\t} : +\t\tfunction( a, b ) { +\t\t\tif ( b ) { +\t\t\t\twhile ( (b = b.parentNode) ) { +\t\t\t\t\tif ( b === a ) { +\t\t\t\t\t\treturn true; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t\treturn false; +\t\t}; + +\t// Document order sorting +\tsortOrder = docElem.compareDocumentPosition ? +\tfunction( a, b ) { +\t\tvar compare; + +\t\tif ( a === b ) { +\t\t\thasDuplicate = true; +\t\t\treturn 0; +\t\t} + +\t\tif ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { +\t\t\tif ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { +\t\t\t\tif ( a === doc || contains( preferredDoc, a ) ) { +\t\t\t\t\treturn -1; +\t\t\t\t} +\t\t\t\tif ( b === doc || contains( preferredDoc, b ) ) { +\t\t\t\t\treturn 1; +\t\t\t\t} +\t\t\t\treturn 0; +\t\t\t} +\t\t\treturn compare & 4 ? -1 : 1; +\t\t} + +\t\treturn a.compareDocumentPosition ? -1 : 1; +\t} : +\tfunction( a, b ) { +\t\tvar cur, +\t\t\ti = 0, +\t\t\taup = a.parentNode, +\t\t\tbup = b.parentNode, +\t\t\tap = [ a ], +\t\t\tbp = [ b ]; + +\t\t// Exit early if the nodes are identical +\t\tif ( a === b ) { +\t\t\thasDuplicate = true; +\t\t\treturn 0; + +\t\t// Parentless nodes are either documents or disconnected +\t\t} else if ( !aup || !bup ) { +\t\t\treturn a === doc ? -1 : +\t\t\t\tb === doc ? 1 : +\t\t\t\taup ? -1 : +\t\t\t\tbup ? 1 : +\t\t\t\t0; + +\t\t// If the nodes are siblings, we can do a quick check +\t\t} else if ( aup === bup ) { +\t\t\treturn siblingCheck( a, b ); +\t\t} + +\t\t// Otherwise we need full lists of their ancestors for comparison +\t\tcur = a; +\t\twhile ( (cur = cur.parentNode) ) { +\t\t\tap.unshift( cur ); +\t\t} +\t\tcur = b; +\t\twhile ( (cur = cur.parentNode) ) { +\t\t\tbp.unshift( cur ); +\t\t} + +\t\t// Walk down the tree looking for a discrepancy +\t\twhile ( ap[i] === bp[i] ) { +\t\t\ti++; +\t\t} + +\t\treturn i ? +\t\t\t// Do a sibling check if the nodes have a common ancestor +\t\t\tsiblingCheck( ap[i], bp[i] ) : + +\t\t\t// Otherwise nodes in our document sort first +\t\t\tap[i] === preferredDoc ? -1 : +\t\t\tbp[i] === preferredDoc ? 1 : +\t\t\t0; +\t}; + +\t// Always assume the presence of duplicates if sort doesn't +\t// pass them to our comparison function (as in Google Chrome). +\thasDuplicate = false; +\t[0, 0].sort( sortOrder ); +\tsupport.detectDuplicates = hasDuplicate; + +\treturn document; }; Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); +\treturn Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - - // rbuggyQSA always contains :focus, so no need for an existence check - if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch(e) {} - } - - return Sizzle( expr, document, null, [elem] ).length > 0; +\t// Set document vars if needed +\tif ( ( elem.ownerDocument || elem ) !== document ) { +\t\tsetDocument( elem ); +\t} + +\t// Make sure that attribute selectors are quoted +\texpr = expr.replace( rattributeQuotes, "='$1']" ); + +\t// rbuggyQSA always contains :focus, so no need for an existence check +\tif ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { +\t\ttry { +\t\t\tvar ret = matches.call( elem, expr ); + +\t\t\t// IE 9's matchesSelector returns false on disconnected nodes +\t\t\tif ( ret || support.disconnectedMatch || +\t\t\t\t\t// As well, disconnected nodes are said to be in a document +\t\t\t\t\t// fragment in IE 9 +\t\t\t\t\telem.document && elem.document.nodeType !== 11 ) { +\t\t\t\treturn ret; +\t\t\t} +\t\t} catch(e) {} +\t} + +\treturn Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); +\t// Set document vars if needed +\tif ( ( context.ownerDocument || context ) !== document ) { +\t\tsetDocument( context ); +\t} +\treturn contains( context, elem ); }; Sizzle.attr = function( elem, name ) { - var val; - - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - if ( !documentIsXML ) { - name = name.toLowerCase(); - } - if ( (val = Expr.attrHandle[ name ]) ) { - return val( elem ); - } - if ( documentIsXML || support.attributes ) { - return elem.getAttribute( name ); - } - return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? - name : - val && val.specified ? val.value : null; +\tvar val; + +\t// Set document vars if needed +\tif ( ( elem.ownerDocument || elem ) !== document ) { +\t\tsetDocument( elem ); +\t} + +\tif ( !documentIsXML ) { +\t\tname = name.toLowerCase(); +\t} +\tif ( (val = Expr.attrHandle[ name ]) ) { +\t\treturn val( elem ); +\t} +\tif ( documentIsXML || support.attributes ) { +\t\treturn elem.getAttribute( name ); +\t} +\treturn ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? +\t\tname : +\t\tval && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); +\tthrow new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - i = 1, - j = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( ; (elem = results[i]); i++ ) { - if ( elem === results[ i - 1 ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - return results; +\tvar elem, +\t\tduplicates = [], +\t\ti = 1, +\t\tj = 0; + +\t// Unless we *know* we can detect duplicates, assume their presence +\thasDuplicate = !support.detectDuplicates; +\tresults.sort( sortOrder ); + +\tif ( hasDuplicate ) { +\t\tfor ( ; (elem = results[i]); i++ ) { +\t\t\tif ( elem === results[ i - 1 ] ) { +\t\t\t\tj = duplicates.push( i ); +\t\t\t} +\t\t} +\t\twhile ( j-- ) { +\t\t\tresults.splice( duplicates[ j ], 1 ); +\t\t} +\t} + +\treturn results; }; function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; +\tvar cur = b && a, +\t\tdiff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); + +\t// Use IE sourceIndex if available on both nodes +\tif ( diff ) { +\t\treturn diff; +\t} + +\t// Check if b follows a +\tif ( cur ) { +\t\twhile ( (cur = cur.nextSibling) ) { +\t\t\tif ( cur === b ) { +\t\t\t\treturn -1; +\t\t\t} +\t\t} +\t} + +\treturn a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; +\treturn function( elem ) { +\t\tvar name = elem.nodeName.toLowerCase(); +\t\treturn name === "input" && elem.type === type; +\t}; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; +\treturn function( elem ) { +\t\tvar name = elem.nodeName.toLowerCase(); +\t\treturn (name === "input" || name === "button") && elem.type === type; +\t}; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); +\treturn markFunction(function( argument ) { +\t\targument = +argument; +\t\treturn markFunction(function( seed, matches ) { +\t\t\tvar j, +\t\t\t\tmatchIndexes = fn( [], seed.length, argument ), +\t\t\t\ti = matchIndexes.length; + +\t\t\t// Match elements found at the specified indexes +\t\t\twhile ( i-- ) { +\t\t\t\tif ( seed[ (j = matchIndexes[i]) ] ) { +\t\t\t\t\tseed[j] = !(matches[j] = seed[j]); +\t\t\t\t} +\t\t\t} +\t\t}); +\t}); } /** @@ -4507,1017 +4507,1017 @@ function createPositionalPseudo( fn ) { * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - for ( ; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (see #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; +\tvar node, +\t\tret = "", +\t\ti = 0, +\t\tnodeType = elem.nodeType; + +\tif ( !nodeType ) { +\t\t// If no nodeType, this is expected to be an array +\t\tfor ( ; (node = elem[i]); i++ ) { +\t\t\t// Do not traverse comment nodes +\t\t\tret += getText( node ); +\t\t} +\t} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { +\t\t// Use textContent for elements +\t\t// innerText usage removed for consistency of new lines (see #11153) +\t\tif ( typeof elem.textContent === "string" ) { +\t\t\treturn elem.textContent; +\t\t} else { +\t\t\t// Traverse its children +\t\t\tfor ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { +\t\t\t\tret += getText( elem ); +\t\t\t} +\t\t} +\t} else if ( nodeType === 3 || nodeType === 4 ) { +\t\treturn elem.nodeValue; +\t} +\t// Do not include comment or processing instruction nodes + +\treturn ret; }; Expr = Sizzle.selectors = { - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); - - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); - - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); - - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[5] && match[2]; - - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[4] ) { - match[2] = match[4]; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeName ) { - if ( nodeName === "*" ) { - return function() { return true; }; - } - - nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); - }); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, - - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, context, xml ) { - var cache, outerCache, node, diff, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - // Seek `elem` from a previously-cached index - outerCache = parent[ expando ] || (parent[ expando ] = {}); - cache = outerCache[ type ] || []; - nodeIndex = cache[0] === dirruns && cache[1]; - diff = cache[0] === dirruns && cache[2]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( (node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - outerCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - // Use previously-cached element index if available - } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { - diff = cache[1]; - - // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) - } else { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { - // Cache the index of each encountered element - if ( useCache ) { - (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf.call( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); - } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); - } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - return !results.pop(); - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - - "contains": markFunction(function( text ) { - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifider - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsXML ? - elem.getAttribute("xml:lang") || elem.getAttribute("lang") : - elem.lang) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": function( elem ) { - return elem.disabled === false; - }, - - "disabled": function( elem ) { - return elem.disabled === true; - }, - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), - // not comment, processing instructions, or others - // Thanks to Diego Perini for the nodeName shortcut - // Greater than "@" means alpha characters (specifically not starting with "#" or "?") - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); - }, - - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), - - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), - - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), - - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }) - } +\t// Can be adjusted by the user +\tcacheLength: 50, + +\tcreatePseudo: markFunction, + +\tmatch: matchExpr, + +\tfind: {}, + +\trelative: { +\t\t">": { dir: "parentNode", first: true }, +\t\t" ": { dir: "parentNode" }, +\t\t"+": { dir: "previousSibling", first: true }, +\t\t"~": { dir: "previousSibling" } +\t}, + +\tpreFilter: { +\t\t"ATTR": function( match ) { +\t\t\tmatch[1] = match[1].replace( runescape, funescape ); + +\t\t\t// Move the given value to match[3] whether quoted or unquoted +\t\t\tmatch[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + +\t\t\tif ( match[2] === "~=" ) { +\t\t\t\tmatch[3] = " " + match[3] + " "; +\t\t\t} + +\t\t\treturn match.slice( 0, 4 ); +\t\t}, + +\t\t"CHILD": function( match ) { +\t\t\t/* matches from matchExpr["CHILD"] +\t\t\t\t1 type (only|nth|...) +\t\t\t\t2 what (child|of-type) +\t\t\t\t3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) +\t\t\t\t4 xn-component of xn+y argument ([+-]?\d*n|) +\t\t\t\t5 sign of xn-component +\t\t\t\t6 x of xn-component +\t\t\t\t7 sign of y-component +\t\t\t\t8 y of y-component +\t\t\t*/ +\t\t\tmatch[1] = match[1].toLowerCase(); + +\t\t\tif ( match[1].slice( 0, 3 ) === "nth" ) { +\t\t\t\t// nth-* requires argument +\t\t\t\tif ( !match[3] ) { +\t\t\t\t\tSizzle.error( match[0] ); +\t\t\t\t} + +\t\t\t\t// numeric x and y parameters for Expr.filter.CHILD +\t\t\t\t// remember that false/true cast respectively to 0/1 +\t\t\t\tmatch[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); +\t\t\t\tmatch[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + +\t\t\t// other types prohibit arguments +\t\t\t} else if ( match[3] ) { +\t\t\t\tSizzle.error( match[0] ); +\t\t\t} + +\t\t\treturn match; +\t\t}, + +\t\t"PSEUDO": function( match ) { +\t\t\tvar excess, +\t\t\t\tunquoted = !match[5] && match[2]; + +\t\t\tif ( matchExpr["CHILD"].test( match[0] ) ) { +\t\t\t\treturn null; +\t\t\t} + +\t\t\t// Accept quoted arguments as-is +\t\t\tif ( match[4] ) { +\t\t\t\tmatch[2] = match[4]; + +\t\t\t// Strip excess characters from unquoted arguments +\t\t\t} else if ( unquoted && rpseudo.test( unquoted ) && +\t\t\t\t// Get excess from tokenize (recursively) +\t\t\t\t(excess = tokenize( unquoted, true )) && +\t\t\t\t// advance to the next closing parenthesis +\t\t\t\t(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + +\t\t\t\t// excess is a negative index +\t\t\t\tmatch[0] = match[0].slice( 0, excess ); +\t\t\t\tmatch[2] = unquoted.slice( 0, excess ); +\t\t\t} + +\t\t\t// Return only captures needed by the pseudo filter method (type and argument) +\t\t\treturn match.slice( 0, 3 ); +\t\t} +\t}, + +\tfilter: { + +\t\t"TAG": function( nodeName ) { +\t\t\tif ( nodeName === "*" ) { +\t\t\t\treturn function() { return true; }; +\t\t\t} + +\t\t\tnodeName = nodeName.replace( runescape, funescape ).toLowerCase(); +\t\t\treturn function( elem ) { +\t\t\t\treturn elem.nodeName && elem.nodeName.toLowerCase() === nodeName; +\t\t\t}; +\t\t}, + +\t\t"CLASS": function( className ) { +\t\t\tvar pattern = classCache[ className + " " ]; + +\t\t\treturn pattern || +\t\t\t\t(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && +\t\t\t\tclassCache( className, function( elem ) { +\t\t\t\t\treturn pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); +\t\t\t\t}); +\t\t}, + +\t\t"ATTR": function( name, operator, check ) { +\t\t\treturn function( elem ) { +\t\t\t\tvar result = Sizzle.attr( elem, name ); + +\t\t\t\tif ( result == null ) { +\t\t\t\t\treturn operator === "!="; +\t\t\t\t} +\t\t\t\tif ( !operator ) { +\t\t\t\t\treturn true; +\t\t\t\t} + +\t\t\t\tresult += ""; + +\t\t\t\treturn operator === "=" ? result === check : +\t\t\t\t\toperator === "!=" ? result !== check : +\t\t\t\t\toperator === "^=" ? check && result.indexOf( check ) === 0 : +\t\t\t\t\toperator === "*=" ? check && result.indexOf( check ) > -1 : +\t\t\t\t\toperator === "$=" ? check && result.slice( -check.length ) === check : +\t\t\t\t\toperator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : +\t\t\t\t\toperator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : +\t\t\t\t\tfalse; +\t\t\t}; +\t\t}, + +\t\t"CHILD": function( type, what, argument, first, last ) { +\t\t\tvar simple = type.slice( 0, 3 ) !== "nth", +\t\t\t\tforward = type.slice( -4 ) !== "last", +\t\t\t\tofType = what === "of-type"; + +\t\t\treturn first === 1 && last === 0 ? + +\t\t\t\t// Shortcut for :nth-*(n) +\t\t\t\tfunction( elem ) { +\t\t\t\t\treturn !!elem.parentNode; +\t\t\t\t} : + +\t\t\t\tfunction( elem, context, xml ) { +\t\t\t\t\tvar cache, outerCache, node, diff, nodeIndex, start, +\t\t\t\t\t\tdir = simple !== forward ? "nextSibling" : "previousSibling", +\t\t\t\t\t\tparent = elem.parentNode, +\t\t\t\t\t\tname = ofType && elem.nodeName.toLowerCase(), +\t\t\t\t\t\tuseCache = !xml && !ofType; + +\t\t\t\t\tif ( parent ) { + +\t\t\t\t\t\t// :(first|last|only)-(child|of-type) +\t\t\t\t\t\tif ( simple ) { +\t\t\t\t\t\t\twhile ( dir ) { +\t\t\t\t\t\t\t\tnode = elem; +\t\t\t\t\t\t\t\twhile ( (node = node[ dir ]) ) { +\t\t\t\t\t\t\t\t\tif ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { +\t\t\t\t\t\t\t\t\t\treturn false; +\t\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t\t// Reverse direction for :only-* (if we haven't yet done so) +\t\t\t\t\t\t\t\tstart = dir = type === "only" && !start && "nextSibling"; +\t\t\t\t\t\t\t} +\t\t\t\t\t\t\treturn true; +\t\t\t\t\t\t} + +\t\t\t\t\t\tstart = [ forward ? parent.firstChild : parent.lastChild ]; + +\t\t\t\t\t\t// non-xml :nth-child(...) stores cache data on `parent` +\t\t\t\t\t\tif ( forward && useCache ) { +\t\t\t\t\t\t\t// Seek `elem` from a previously-cached index +\t\t\t\t\t\t\touterCache = parent[ expando ] || (parent[ expando ] = {}); +\t\t\t\t\t\t\tcache = outerCache[ type ] || []; +\t\t\t\t\t\t\tnodeIndex = cache[0] === dirruns && cache[1]; +\t\t\t\t\t\t\tdiff = cache[0] === dirruns && cache[2]; +\t\t\t\t\t\t\tnode = nodeIndex && parent.childNodes[ nodeIndex ]; + +\t\t\t\t\t\t\twhile ( (node = ++nodeIndex && node && node[ dir ] || + +\t\t\t\t\t\t\t\t// Fallback to seeking `elem` from the start +\t\t\t\t\t\t\t\t(diff = nodeIndex = 0) || start.pop()) ) { + +\t\t\t\t\t\t\t\t// When found, cache indexes on `parent` and break +\t\t\t\t\t\t\t\tif ( node.nodeType === 1 && ++diff && node === elem ) { +\t\t\t\t\t\t\t\t\touterCache[ type ] = [ dirruns, nodeIndex, diff ]; +\t\t\t\t\t\t\t\t\tbreak; +\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t} + +\t\t\t\t\t\t// Use previously-cached element index if available +\t\t\t\t\t\t} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { +\t\t\t\t\t\t\tdiff = cache[1]; + +\t\t\t\t\t\t// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) +\t\t\t\t\t\t} else { +\t\t\t\t\t\t\t// Use the same loop as above to seek `elem` from the start +\t\t\t\t\t\t\twhile ( (node = ++nodeIndex && node && node[ dir ] || +\t\t\t\t\t\t\t\t(diff = nodeIndex = 0) || start.pop()) ) { + +\t\t\t\t\t\t\t\tif ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { +\t\t\t\t\t\t\t\t\t// Cache the index of each encountered element +\t\t\t\t\t\t\t\t\tif ( useCache ) { +\t\t\t\t\t\t\t\t\t\t(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; +\t\t\t\t\t\t\t\t\t} + +\t\t\t\t\t\t\t\t\tif ( node === elem ) { +\t\t\t\t\t\t\t\t\t\tbreak; +\t\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t\t} +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} + +\t\t\t\t\t\t// Incorporate the offset, then check against cycle size +\t\t\t\t\t\tdiff -= last; +\t\t\t\t\t\treturn diff === first || ( diff % first === 0 && diff / first >= 0 ); +\t\t\t\t\t} +\t\t\t\t}; +\t\t}, + +\t\t"PSEUDO": function( pseudo, argument ) { +\t\t\t// pseudo-class names are case-insensitive +\t\t\t// http://www.w3.org/TR/selectors/#pseudo-classes +\t\t\t// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters +\t\t\t// Remember that setFilters inherits from pseudos +\t\t\tvar args, +\t\t\t\tfn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || +\t\t\t\t\tSizzle.error( "unsupported pseudo: " + pseudo ); + +\t\t\t// The user may use createPseudo to indicate that +\t\t\t// arguments are needed to create the filter function +\t\t\t// just as Sizzle does +\t\t\tif ( fn[ expando ] ) { +\t\t\t\treturn fn( argument ); +\t\t\t} + +\t\t\t// But maintain support for old signatures +\t\t\tif ( fn.length > 1 ) { +\t\t\t\targs = [ pseudo, pseudo, "", argument ]; +\t\t\t\treturn Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? +\t\t\t\t\tmarkFunction(function( seed, matches ) { +\t\t\t\t\t\tvar idx, +\t\t\t\t\t\t\tmatched = fn( seed, argument ), +\t\t\t\t\t\t\ti = matched.length; +\t\t\t\t\t\twhile ( i-- ) { +\t\t\t\t\t\t\tidx = indexOf.call( seed, matched[i] ); +\t\t\t\t\t\t\tseed[ idx ] = !( matches[ idx ] = matched[i] ); +\t\t\t\t\t\t} +\t\t\t\t\t}) : +\t\t\t\t\tfunction( elem ) { +\t\t\t\t\t\treturn fn( elem, 0, args ); +\t\t\t\t\t}; +\t\t\t} + +\t\t\treturn fn; +\t\t} +\t}, + +\tpseudos: { +\t\t// Potentially complex pseudos +\t\t"not": markFunction(function( selector ) { +\t\t\t// Trim the selector passed to compile +\t\t\t// to avoid treating leading and trailing +\t\t\t// spaces as combinators +\t\t\tvar input = [], +\t\t\t\tresults = [], +\t\t\t\tmatcher = compile( selector.replace( rtrim, "$1" ) ); + +\t\t\treturn matcher[ expando ] ? +\t\t\t\tmarkFunction(function( seed, matches, context, xml ) { +\t\t\t\t\tvar elem, +\t\t\t\t\t\tunmatched = matcher( seed, null, xml, [] ), +\t\t\t\t\t\ti = seed.length; + +\t\t\t\t\t// Match elements unmatched by `matcher` +\t\t\t\t\twhile ( i-- ) { +\t\t\t\t\t\tif ( (elem = unmatched[i]) ) { +\t\t\t\t\t\t\tseed[i] = !(matches[i] = elem); +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t}) : +\t\t\t\tfunction( elem, context, xml ) { +\t\t\t\t\tinput[0] = elem; +\t\t\t\t\tmatcher( input, null, xml, results ); +\t\t\t\t\treturn !results.pop(); +\t\t\t\t}; +\t\t}), + +\t\t"has": markFunction(function( selector ) { +\t\t\treturn function( elem ) { +\t\t\t\treturn Sizzle( selector, elem ).length > 0; +\t\t\t}; +\t\t}), + +\t\t"contains": markFunction(function( text ) { +\t\t\treturn function( elem ) { +\t\t\t\treturn ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; +\t\t\t}; +\t\t}), + +\t\t// "Whether an element is represented by a :lang() selector +\t\t// is based solely on the element's language value +\t\t// being equal to the identifier C, +\t\t// or beginning with the identifier C immediately followed by "-". +\t\t// The matching of C against the element's language value is performed case-insensitively. +\t\t// The identifier C does not have to be a valid language name." +\t\t// http://www.w3.org/TR/selectors/#lang-pseudo +\t\t"lang": markFunction( function( lang ) { +\t\t\t// lang value must be a valid identifider +\t\t\tif ( !ridentifier.test(lang || "") ) { +\t\t\t\tSizzle.error( "unsupported lang: " + lang ); +\t\t\t} +\t\t\tlang = lang.replace( runescape, funescape ).toLowerCase(); +\t\t\treturn function( elem ) { +\t\t\t\tvar elemLang; +\t\t\t\tdo { +\t\t\t\t\tif ( (elemLang = documentIsXML ? +\t\t\t\t\t\telem.getAttribute("xml:lang") || elem.getAttribute("lang") : +\t\t\t\t\t\telem.lang) ) { + +\t\t\t\t\t\telemLang = elemLang.toLowerCase(); +\t\t\t\t\t\treturn elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; +\t\t\t\t\t} +\t\t\t\t} while ( (elem = elem.parentNode) && elem.nodeType === 1 ); +\t\t\t\treturn false; +\t\t\t}; +\t\t}), + +\t\t// Miscellaneous +\t\t"target": function( elem ) { +\t\t\tvar hash = window.location && window.location.hash; +\t\t\treturn hash && hash.slice( 1 ) === elem.id; +\t\t}, + +\t\t"root": function( elem ) { +\t\t\treturn elem === docElem; +\t\t}, + +\t\t"focus": function( elem ) { +\t\t\treturn elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); +\t\t}, + +\t\t// Boolean properties +\t\t"enabled": function( elem ) { +\t\t\treturn elem.disabled === false; +\t\t}, + +\t\t"disabled": function( elem ) { +\t\t\treturn elem.disabled === true; +\t\t}, + +\t\t"checked": function( elem ) { +\t\t\t// In CSS3, :checked should return both checked and selected elements +\t\t\t// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked +\t\t\tvar nodeName = elem.nodeName.toLowerCase(); +\t\t\treturn (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); +\t\t}, + +\t\t"selected": function( elem ) { +\t\t\t// Accessing this property makes selected-by-default +\t\t\t// options in Safari work properly +\t\t\tif ( elem.parentNode ) { +\t\t\t\telem.parentNode.selectedIndex; +\t\t\t} + +\t\t\treturn elem.selected === true; +\t\t}, + +\t\t// Contents +\t\t"empty": function( elem ) { +\t\t\t// http://www.w3.org/TR/selectors/#empty-pseudo +\t\t\t// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), +\t\t\t// not comment, processing instructions, or others +\t\t\t// Thanks to Diego Perini for the nodeName shortcut +\t\t\t// Greater than "@" means alpha characters (specifically not starting with "#" or "?") +\t\t\tfor ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { +\t\t\t\tif ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { +\t\t\t\t\treturn false; +\t\t\t\t} +\t\t\t} +\t\t\treturn true; +\t\t}, + +\t\t"parent": function( elem ) { +\t\t\treturn !Expr.pseudos["empty"]( elem ); +\t\t}, + +\t\t// Element/input types +\t\t"header": function( elem ) { +\t\t\treturn rheader.test( elem.nodeName ); +\t\t}, + +\t\t"input": function( elem ) { +\t\t\treturn rinputs.test( elem.nodeName ); +\t\t}, + +\t\t"button": function( elem ) { +\t\t\tvar name = elem.nodeName.toLowerCase(); +\t\t\treturn name === "input" && elem.type === "button" || name === "button"; +\t\t}, + +\t\t"text": function( elem ) { +\t\t\tvar attr; +\t\t\t// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) +\t\t\t// use getAttribute instead to test this case +\t\t\treturn elem.nodeName.toLowerCase() === "input" && +\t\t\t\telem.type === "text" && +\t\t\t\t( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); +\t\t}, + +\t\t// Position-in-collection +\t\t"first": createPositionalPseudo(function() { +\t\t\treturn [ 0 ]; +\t\t}), + +\t\t"last": createPositionalPseudo(function( matchIndexes, length ) { +\t\t\treturn [ length - 1 ]; +\t\t}), + +\t\t"eq": createPositionalPseudo(function( matchIndexes, length, argument ) { +\t\t\treturn [ argument < 0 ? argument + length : argument ]; +\t\t}), + +\t\t"even": createPositionalPseudo(function( matchIndexes, length ) { +\t\t\tvar i = 0; +\t\t\tfor ( ; i < length; i += 2 ) { +\t\t\t\tmatchIndexes.push( i ); +\t\t\t} +\t\t\treturn matchIndexes; +\t\t}), + +\t\t"odd": createPositionalPseudo(function( matchIndexes, length ) { +\t\t\tvar i = 1; +\t\t\tfor ( ; i < length; i += 2 ) { +\t\t\t\tmatchIndexes.push( i ); +\t\t\t} +\t\t\treturn matchIndexes; +\t\t}), + +\t\t"lt": createPositionalPseudo(function( matchIndexes, length, argument ) { +\t\t\tvar i = argument < 0 ? argument + length : argument; +\t\t\tfor ( ; --i >= 0; ) { +\t\t\t\tmatchIndexes.push( i ); +\t\t\t} +\t\t\treturn matchIndexes; +\t\t}), + +\t\t"gt": createPositionalPseudo(function( matchIndexes, length, argument ) { +\t\t\tvar i = argument < 0 ? argument + length : argument; +\t\t\tfor ( ; ++i < length; ) { +\t\t\t\tmatchIndexes.push( i ); +\t\t\t} +\t\t\treturn matchIndexes; +\t\t}) +\t} }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); +\tExpr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); +\tExpr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; - } - groups.push( tokens = [] ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push( { - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - } ); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push( { - value: matched, - type: type, - matches: match - } ); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); +\tvar matched, match, tokens, type, +\t\tsoFar, groups, preFilters, +\t\tcached = tokenCache[ selector + " " ]; + +\tif ( cached ) { +\t\treturn parseOnly ? 0 : cached.slice( 0 ); +\t} + +\tsoFar = selector; +\tgroups = []; +\tpreFilters = Expr.preFilter; + +\twhile ( soFar ) { + +\t\t// Comma and first run +\t\tif ( !matched || (match = rcomma.exec( soFar )) ) { +\t\t\tif ( match ) { +\t\t\t\t// Don't consume trailing commas as valid +\t\t\t\tsoFar = soFar.slice( match[0].length ) || soFar; +\t\t\t} +\t\t\tgroups.push( tokens = [] ); +\t\t} + +\t\tmatched = false; + +\t\t// Combinators +\t\tif ( (match = rcombinators.exec( soFar )) ) { +\t\t\tmatched = match.shift(); +\t\t\ttokens.push( { +\t\t\t\tvalue: matched, +\t\t\t\t// Cast descendant combinators to space +\t\t\t\ttype: match[0].replace( rtrim, " " ) +\t\t\t} ); +\t\t\tsoFar = soFar.slice( matched.length ); +\t\t} + +\t\t// Filters +\t\tfor ( type in Expr.filter ) { +\t\t\tif ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || +\t\t\t\t(match = preFilters[ type ]( match ))) ) { +\t\t\t\tmatched = match.shift(); +\t\t\t\ttokens.push( { +\t\t\t\t\tvalue: matched, +\t\t\t\t\ttype: type, +\t\t\t\t\tmatches: match +\t\t\t\t} ); +\t\t\t\tsoFar = soFar.slice( matched.length ); +\t\t\t} +\t\t} + +\t\tif ( !matched ) { +\t\t\tbreak; +\t\t} +\t} + +\t// Return the length of the invalid excess +\t// if we're just parsing +\t// Otherwise, throw an error or return tokens +\treturn parseOnly ? +\t\tsoFar.length : +\t\tsoFar ? +\t\t\tSizzle.error( selector ) : +\t\t\t// Cache the tokens +\t\t\ttokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; +\tvar i = 0, +\t\tlen = tokens.length, +\t\tselector = ""; +\tfor ( ; i < len; i++ ) { +\t\tselector += tokens[i].value; +\t} +\treturn selector; } function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - checkNonElements = base && dir === "parentNode", - doneName = done++; - - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var data, cache, outerCache, - dirkey = dirruns + " " + doneName; - - // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { - if ( (data = cache[1]) === true || data === cachedruns ) { - return data === true; - } - } else { - cache = outerCache[ dir ] = [ dirkey ]; - cache[1] = matcher( elem, context, xml ) || cachedruns; - if ( cache[1] === true ) { - return true; - } - } - } - } - } - }; +\tvar dir = combinator.dir, +\t\tcheckNonElements = base && dir === "parentNode", +\t\tdoneName = done++; + +\treturn combinator.first ? +\t\t// Check against closest ancestor/preceding element +\t\tfunction( elem, context, xml ) { +\t\t\twhile ( (elem = elem[ dir ]) ) { +\t\t\t\tif ( elem.nodeType === 1 || checkNonElements ) { +\t\t\t\t\treturn matcher( elem, context, xml ); +\t\t\t\t} +\t\t\t} +\t\t} : + +\t\t// Check against all ancestor/preceding elements +\t\tfunction( elem, context, xml ) { +\t\t\tvar data, cache, outerCache, +\t\t\t\tdirkey = dirruns + " " + doneName; + +\t\t\t// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching +\t\t\tif ( xml ) { +\t\t\t\twhile ( (elem = elem[ dir ]) ) { +\t\t\t\t\tif ( elem.nodeType === 1 || checkNonElements ) { +\t\t\t\t\t\tif ( matcher( elem, context, xml ) ) { +\t\t\t\t\t\t\treturn true; +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} else { +\t\t\t\twhile ( (elem = elem[ dir ]) ) { +\t\t\t\t\tif ( elem.nodeType === 1 || checkNonElements ) { +\t\t\t\t\t\touterCache = elem[ expando ] || (elem[ expando ] = {}); +\t\t\t\t\t\tif ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { +\t\t\t\t\t\t\tif ( (data = cache[1]) === true || data === cachedruns ) { +\t\t\t\t\t\t\t\treturn data === true; +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} else { +\t\t\t\t\t\t\tcache = outerCache[ dir ] = [ dirkey ]; +\t\t\t\t\t\t\tcache[1] = matcher( elem, context, xml ) || cachedruns; +\t\t\t\t\t\t\tif ( cache[1] === true ) { +\t\t\t\t\t\t\t\treturn true; +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t}; } function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[0]; +\treturn matchers.length > 1 ? +\t\tfunction( elem, context, xml ) { +\t\t\tvar i = matchers.length; +\t\t\twhile ( i-- ) { +\t\t\t\tif ( !matchers[i]( elem, context, xml ) ) { +\t\t\t\t\treturn false; +\t\t\t\t} +\t\t\t} +\t\t\treturn true; +\t\t} : +\t\tmatchers[0]; } function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; +\tvar elem, +\t\tnewUnmatched = [], +\t\ti = 0, +\t\tlen = unmatched.length, +\t\tmapped = map != null; + +\tfor ( ; i < len; i++ ) { +\t\tif ( (elem = unmatched[i]) ) { +\t\t\tif ( !filter || filter( elem, context, xml ) ) { +\t\t\t\tnewUnmatched.push( elem ); +\t\t\t\tif ( mapped ) { +\t\t\t\t\tmap.push( i ); +\t\t\t\t} +\t\t\t} +\t\t} +\t} + +\treturn newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); - } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); +\tif ( postFilter && !postFilter[ expando ] ) { +\t\tpostFilter = setMatcher( postFilter ); +\t} +\tif ( postFinder && !postFinder[ expando ] ) { +\t\tpostFinder = setMatcher( postFinder, postSelector ); +\t} +\treturn markFunction(function( seed, results, context, xml ) { +\t\tvar temp, i, elem, +\t\t\tpreMap = [], +\t\t\tpostMap = [], +\t\t\tpreexisting = results.length, + +\t\t\t// Get initial elements from seed or context +\t\t\telems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + +\t\t\t// Prefilter to get matcher input, preserving a map for seed-results synchronization +\t\t\tmatcherIn = preFilter && ( seed || !selector ) ? +\t\t\t\tcondense( elems, preMap, preFilter, context, xml ) : +\t\t\t\telems, + +\t\t\tmatcherOut = matcher ? +\t\t\t\t// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, +\t\t\t\tpostFinder || ( seed ? preFilter : preexisting || postFilter ) ? + +\t\t\t\t\t// ...intermediate processing is necessary +\t\t\t\t\t[] : + +\t\t\t\t\t// ...otherwise use results directly +\t\t\t\t\tresults : +\t\t\t\tmatcherIn; + +\t\t// Find primary matches +\t\tif ( matcher ) { +\t\t\tmatcher( matcherIn, matcherOut, context, xml ); +\t\t} + +\t\t// Apply postFilter +\t\tif ( postFilter ) { +\t\t\ttemp = condense( matcherOut, postMap ); +\t\t\tpostFilter( temp, [], context, xml ); + +\t\t\t// Un-match failing elements by moving them back to matcherIn +\t\t\ti = temp.length; +\t\t\twhile ( i-- ) { +\t\t\t\tif ( (elem = temp[i]) ) { +\t\t\t\t\tmatcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); +\t\t\t\t} +\t\t\t} +\t\t} + +\t\tif ( seed ) { +\t\t\tif ( postFinder || preFilter ) { +\t\t\t\tif ( postFinder ) { +\t\t\t\t\t// Get the final matcherOut by condensing this intermediate into postFinder contexts +\t\t\t\t\ttemp = []; +\t\t\t\t\ti = matcherOut.length; +\t\t\t\t\twhile ( i-- ) { +\t\t\t\t\t\tif ( (elem = matcherOut[i]) ) { +\t\t\t\t\t\t\t// Restore matcherIn since elem is not yet a final match +\t\t\t\t\t\t\ttemp.push( (matcherIn[i] = elem) ); +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t\tpostFinder( null, (matcherOut = []), temp, xml ); +\t\t\t\t} + +\t\t\t\t// Move matched elements from seed to results to keep them synchronized +\t\t\t\ti = matcherOut.length; +\t\t\t\twhile ( i-- ) { +\t\t\t\t\tif ( (elem = matcherOut[i]) && +\t\t\t\t\t\t(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + +\t\t\t\t\t\tseed[temp] = !(results[temp] = elem); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} + +\t\t// Add elements to results, through postFinder if defined +\t\t} else { +\t\t\tmatcherOut = condense( +\t\t\t\tmatcherOut === results ? +\t\t\t\t\tmatcherOut.splice( preexisting, matcherOut.length ) : +\t\t\t\t\tmatcherOut +\t\t\t); +\t\t\tif ( postFinder ) { +\t\t\t\tpostFinder( null, results, matcherOut, xml ); +\t\t\t} else { +\t\t\t\tpush.apply( results, matcherOut ); +\t\t\t} +\t\t} +\t}); } function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf.call( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); +\tvar checkContext, matcher, j, +\t\tlen = tokens.length, +\t\tleadingRelative = Expr.relative[ tokens[0].type ], +\t\timplicitRelative = leadingRelative || Expr.relative[" "], +\t\ti = leadingRelative ? 1 : 0, + +\t\t// The foundational matcher ensures that elements are reachable from top-level context(s) +\t\tmatchContext = addCombinator( function( elem ) { +\t\t\treturn elem === checkContext; +\t\t}, implicitRelative, true ), +\t\tmatchAnyContext = addCombinator( function( elem ) { +\t\t\treturn indexOf.call( checkContext, elem ) > -1; +\t\t}, implicitRelative, true ), +\t\tmatchers = [ function( elem, context, xml ) { +\t\t\treturn ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( +\t\t\t\t(checkContext = context).nodeType ? +\t\t\t\t\tmatchContext( elem, context, xml ) : +\t\t\t\t\tmatchAnyContext( elem, context, xml ) ); +\t\t} ]; + +\tfor ( ; i < len; i++ ) { +\t\tif ( (matcher = Expr.relative[ tokens[i].type ]) ) { +\t\t\tmatchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; +\t\t} else { +\t\t\tmatcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + +\t\t\t// Return special upon seeing a positional matcher +\t\t\tif ( matcher[ expando ] ) { +\t\t\t\t// Find the next relative operator (if any) for proper handling +\t\t\t\tj = ++i; +\t\t\t\tfor ( ; j < len; j++ ) { +\t\t\t\t\tif ( Expr.relative[ tokens[j].type ] ) { +\t\t\t\t\t\tbreak; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t\treturn setMatcher( +\t\t\t\t\ti > 1 && elementMatcher( matchers ), +\t\t\t\t\ti > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), +\t\t\t\t\tmatcher, +\t\t\t\t\ti < j && matcherFromTokens( tokens.slice( i, j ) ), +\t\t\t\t\tj < len && matcherFromTokens( (tokens = tokens.slice( j )) ), +\t\t\t\t\tj < len && toSelector( tokens ) +\t\t\t\t); +\t\t\t} +\t\t\tmatchers.push( matcher ); +\t\t} +\t} + +\treturn elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - // A counter to specify which element is currently being matched - var matcherCachedRuns = 0, - bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, expandContext ) { - var elem, j, matcher, - setMatched = [], - matchedCount = 0, - i = "0", - unmatched = seed && [], - outermost = expandContext != null, - contextBackup = outermostContext, - // We must always have either seed elements or context - elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); - - if ( outermost ) { - outermostContext = context !== document && context; - cachedruns = matcherCachedRuns; - } - - // Add elements passing elementMatchers directly to results - // Keep `i` a string if there are no elements so `matchedCount` will be "00" below - for ( ; (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context, xml ) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - cachedruns = ++matcherCachedRuns; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // Apply set filters to unmatched elements - matchedCount += i; - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; +\t// A counter to specify which element is currently being matched +\tvar matcherCachedRuns = 0, +\t\tbySet = setMatchers.length > 0, +\t\tbyElement = elementMatchers.length > 0, +\t\tsuperMatcher = function( seed, context, xml, results, expandContext ) { +\t\t\tvar elem, j, matcher, +\t\t\t\tsetMatched = [], +\t\t\t\tmatchedCount = 0, +\t\t\t\ti = "0", +\t\t\t\tunmatched = seed && [], +\t\t\t\toutermost = expandContext != null, +\t\t\t\tcontextBackup = outermostContext, +\t\t\t\t// We must always have either seed elements or context +\t\t\t\telems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), +\t\t\t\t// Use integer dirruns iff this is the outermost matcher +\t\t\t\tdirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + +\t\t\tif ( outermost ) { +\t\t\t\toutermostContext = context !== document && context; +\t\t\t\tcachedruns = matcherCachedRuns; +\t\t\t} + +\t\t\t// Add elements passing elementMatchers directly to results +\t\t\t// Keep `i` a string if there are no elements so `matchedCount` will be "00" below +\t\t\tfor ( ; (elem = elems[i]) != null; i++ ) { +\t\t\t\tif ( byElement && elem ) { +\t\t\t\t\tj = 0; +\t\t\t\t\twhile ( (matcher = elementMatchers[j++]) ) { +\t\t\t\t\t\tif ( matcher( elem, context, xml ) ) { +\t\t\t\t\t\t\tresults.push( elem ); +\t\t\t\t\t\t\tbreak; +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t\tif ( outermost ) { +\t\t\t\t\t\tdirruns = dirrunsUnique; +\t\t\t\t\t\tcachedruns = ++matcherCachedRuns; +\t\t\t\t\t} +\t\t\t\t} + +\t\t\t\t// Track unmatched elements for set filters +\t\t\t\tif ( bySet ) { +\t\t\t\t\t// They will have gone through all possible matchers +\t\t\t\t\tif ( (elem = !matcher && elem) ) { +\t\t\t\t\t\tmatchedCount--; +\t\t\t\t\t} + +\t\t\t\t\t// Lengthen the array for every element, matched or not +\t\t\t\t\tif ( seed ) { +\t\t\t\t\t\tunmatched.push( elem ); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} + +\t\t\t// Apply set filters to unmatched elements +\t\t\tmatchedCount += i; +\t\t\tif ( bySet && i !== matchedCount ) { +\t\t\t\tj = 0; +\t\t\t\twhile ( (matcher = setMatchers[j++]) ) { +\t\t\t\t\tmatcher( unmatched, setMatched, context, xml ); +\t\t\t\t} + +\t\t\t\tif ( seed ) { +\t\t\t\t\t// Reintegrate element matches to eliminate the need for sorting +\t\t\t\t\tif ( matchedCount > 0 ) { +\t\t\t\t\t\twhile ( i-- ) { +\t\t\t\t\t\t\tif ( !(unmatched[i] || setMatched[i]) ) { +\t\t\t\t\t\t\t\tsetMatched[i] = pop.call( results ); +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} +\t\t\t\t\t} + +\t\t\t\t\t// Discard index placeholder values to get only actual matches +\t\t\t\t\tsetMatched = condense( setMatched ); +\t\t\t\t} + +\t\t\t\t// Add matches to results +\t\t\t\tpush.apply( results, setMatched ); + +\t\t\t\t// Seedless set matches succeeding multiple successful matchers stipulate sorting +\t\t\t\tif ( outermost && !seed && setMatched.length > 0 && +\t\t\t\t\t( matchedCount + setMatchers.length ) > 1 ) { + +\t\t\t\t\tSizzle.uniqueSort( results ); +\t\t\t\t} +\t\t\t} + +\t\t\t// Override manipulation of globals by nested matchers +\t\t\tif ( outermost ) { +\t\t\t\tdirruns = dirrunsUnique; +\t\t\t\toutermostContext = contextBackup; +\t\t\t} + +\t\t\treturn unmatched; +\t\t}; + +\treturn bySet ? +\t\tmarkFunction( superMatcher ) : +\t\tsuperMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !group ) { - group = tokenize( selector ); - } - i = group.length; - while ( i-- ) { - cached = matcherFromTokens( group[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - } - return cached; +\tvar i, +\t\tsetMatchers = [], +\t\telementMatchers = [], +\t\tcached = compilerCache[ selector + " " ]; + +\tif ( !cached ) { +\t\t// Generate a function of recursive functions that can be used to check each element +\t\tif ( !group ) { +\t\t\tgroup = tokenize( selector ); +\t\t} +\t\ti = group.length; +\t\twhile ( i-- ) { +\t\t\tcached = matcherFromTokens( group[i] ); +\t\t\tif ( cached[ expando ] ) { +\t\t\t\tsetMatchers.push( cached ); +\t\t\t} else { +\t\t\t\telementMatchers.push( cached ); +\t\t\t} +\t\t} + +\t\t// Cache the compiled function +\t\tcached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); +\t} +\treturn cached; }; function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; +\tvar i = 0, +\t\tlen = contexts.length; +\tfor ( ; i < len; i++ ) { +\t\tSizzle( selector, contexts[i], results ); +\t} +\treturn results; } function select( selector, context, results, seed ) { - var i, tokens, token, type, find, - match = tokenize( selector ); - - if ( !seed ) { - // Try to minimize operations if there is only one group - if ( match.length === 1 ) { - - // Take a shortcut and set the context if the root selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - context.nodeType === 9 && !documentIsXML && - Expr.relative[ tokens[1].type ] ) { - - context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; - if ( !context ) { - return results; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; - - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && context.parentNode || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, slice.call( seed, 0 ) ); - return results; - } - - break; - } - } - } - } - } - - // Compile and execute a filtering function - // Provide `match` to avoid retokenization if we modified the selector above - compile( selector, match )( - seed, - context, - documentIsXML, - results, - rsibling.test( selector ) - ); - return results; +\tvar i, tokens, token, type, find, +\t\tmatch = tokenize( selector ); + +\tif ( !seed ) { +\t\t// Try to minimize operations if there is only one group +\t\tif ( match.length === 1 ) { + +\t\t\t// Take a shortcut and set the context if the root selector is an ID +\t\t\ttokens = match[0] = match[0].slice( 0 ); +\t\t\tif ( tokens.length > 2 && (token = tokens[0]).type === "ID" && +\t\t\t\t\tcontext.nodeType === 9 && !documentIsXML && +\t\t\t\t\tExpr.relative[ tokens[1].type ] ) { + +\t\t\t\tcontext = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; +\t\t\t\tif ( !context ) { +\t\t\t\t\treturn results; +\t\t\t\t} + +\t\t\t\tselector = selector.slice( tokens.shift().value.length ); +\t\t\t} + +\t\t\t// Fetch a seed set for right-to-left matching +\t\t\ti = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; +\t\t\twhile ( i-- ) { +\t\t\t\ttoken = tokens[i]; + +\t\t\t\t// Abort if we hit a combinator +\t\t\t\tif ( Expr.relative[ (type = token.type) ] ) { +\t\t\t\t\tbreak; +\t\t\t\t} +\t\t\t\tif ( (find = Expr.find[ type ]) ) { +\t\t\t\t\t// Search, expanding context for leading sibling combinators +\t\t\t\t\tif ( (seed = find( +\t\t\t\t\t\ttoken.matches[0].replace( runescape, funescape ), +\t\t\t\t\t\trsibling.test( tokens[0].type ) && context.parentNode || context +\t\t\t\t\t)) ) { + +\t\t\t\t\t\t// If seed is empty or no tokens remain, we can return early +\t\t\t\t\t\ttokens.splice( i, 1 ); +\t\t\t\t\t\tselector = seed.length && toSelector( tokens ); +\t\t\t\t\t\tif ( !selector ) { +\t\t\t\t\t\t\tpush.apply( results, slice.call( seed, 0 ) ); +\t\t\t\t\t\t\treturn results; +\t\t\t\t\t\t} + +\t\t\t\t\t\tbreak; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} +\t} + +\t// Compile and execute a filtering function +\t// Provide `match` to avoid retokenization if we modified the selector above +\tcompile( selector, match )( +\t\tseed, +\t\tcontext, +\t\tdocumentIsXML, +\t\tresults, +\t\trsibling.test( selector ) +\t); +\treturn results; } // Deprecated @@ -5544,1919 +5544,1919 @@ jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, - rparentsprev = /^(?:parents|prev(?:Until|All))/, - isSimple = /^.[^:#\[\.,]*$/, - rneedsContext = jQuery.expr.match.needsContext, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; +\trparentsprev = /^(?:parents|prev(?:Until|All))/, +\tisSimple = /^.[^:#\[\.,]*$/, +\trneedsContext = jQuery.expr.match.needsContext, +\t// methods guaranteed to produce a unique set when starting from a unique set +\tguaranteedUnique = { +\t\tchildren: true, +\t\tcontents: true, +\t\tnext: true, +\t\tprev: true +\t}; jQuery.fn.extend({ - find: function( selector ) { - var i, ret, self, - len = this.length; - - if ( typeof selector !== "string" ) { - self = this; - return this.pushStack( jQuery( selector ).filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }) ); - } - - ret = []; - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, this[ i ], ret ); - } - - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; - return ret; - }, - - has: function( target ) { - var i, - targets = jQuery( target, this ), - len = targets.length; - - return this.filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false) ); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true) ); - }, - - is: function( selector ) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - rneedsContext.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - ret = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( ; i < l; i++ ) { - cur = this[i]; - - while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - } - cur = cur.parentNode; - } - } - - return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( jQuery.unique(all) ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - } +\tfind: function( selector ) { +\t\tvar i, ret, self, +\t\t\tlen = this.length; + +\t\tif ( typeof selector !== "string" ) { +\t\t\tself = this; +\t\t\treturn this.pushStack( jQuery( selector ).filter(function() { +\t\t\t\tfor ( i = 0; i < len; i++ ) { +\t\t\t\t\tif ( jQuery.contains( self[ i ], this ) ) { +\t\t\t\t\t\treturn true; +\t\t\t\t\t} +\t\t\t\t} +\t\t\t}) ); +\t\t} + +\t\tret = []; +\t\tfor ( i = 0; i < len; i++ ) { +\t\t\tjQuery.find( selector, this[ i ], ret ); +\t\t} + +\t\t// Needed because $( selector, context ) becomes $( context ).find( selector ) +\t\tret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); +\t\tret.selector = ( this.selector ? this.selector + " " : "" ) + selector; +\t\treturn ret; +\t}, + +\thas: function( target ) { +\t\tvar i, +\t\t\ttargets = jQuery( target, this ), +\t\t\tlen = targets.length; + +\t\treturn this.filter(function() { +\t\t\tfor ( i = 0; i < len; i++ ) { +\t\t\t\tif ( jQuery.contains( this, targets[i] ) ) { +\t\t\t\t\treturn true; +\t\t\t\t} +\t\t\t} +\t\t}); +\t}, + +\tnot: function( selector ) { +\t\treturn this.pushStack( winnow(this, selector, false) ); +\t}, + +\tfilter: function( selector ) { +\t\treturn this.pushStack( winnow(this, selector, true) ); +\t}, + +\tis: function( selector ) { +\t\treturn !!selector && ( +\t\t\ttypeof selector === "string" ? +\t\t\t\t// If this is a positional/relative selector, check membership in the returned set +\t\t\t\t// so $("p:first").is("p:last") won't return true for a doc with two "p". +\t\t\t\trneedsContext.test( selector ) ? +\t\t\t\t\tjQuery( selector, this.context ).index( this[0] ) >= 0 : +\t\t\t\t\tjQuery.filter( selector, this ).length > 0 : +\t\t\t\tthis.filter( selector ).length > 0 ); +\t}, + +\tclosest: function( selectors, context ) { +\t\tvar cur, +\t\t\ti = 0, +\t\t\tl = this.length, +\t\t\tret = [], +\t\t\tpos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? +\t\t\t\tjQuery( selectors, context || this.context ) : +\t\t\t\t0; + +\t\tfor ( ; i < l; i++ ) { +\t\t\tcur = this[i]; + +\t\t\twhile ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { +\t\t\t\tif ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { +\t\t\t\t\tret.push( cur ); +\t\t\t\t\tbreak; +\t\t\t\t} +\t\t\t\tcur = cur.parentNode; +\t\t\t} +\t\t} + +\t\treturn this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); +\t}, + +\t// Determine the position of an element within +\t// the matched set of elements +\tindex: function( elem ) { + +\t\t// No argument, return index in parent +\t\tif ( !elem ) { +\t\t\treturn ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; +\t\t} + +\t\t// index in selector +\t\tif ( typeof elem === "string" ) { +\t\t\treturn jQuery.inArray( this[0], jQuery( elem ) ); +\t\t} + +\t\t// Locate the position of the desired element +\t\treturn jQuery.inArray( +\t\t\t// If it receives a jQuery object, the first element is used +\t\t\telem.jquery ? elem[0] : elem, this ); +\t}, + +\tadd: function( selector, context ) { +\t\tvar set = typeof selector === "string" ? +\t\t\t\tjQuery( selector, context ) : +\t\t\t\tjQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), +\t\t\tall = jQuery.merge( this.get(), set ); + +\t\treturn this.pushStack( jQuery.unique(all) ); +\t}, + +\taddBack: function( selector ) { +\t\treturn this.add( selector == null ? +\t\t\tthis.prevObject : this.prevObject.filter(selector) +\t\t); +\t} }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { - do { - cur = cur[ dir ]; - } while ( cur && cur.nodeType !== 1 ); +\tdo { +\t\tcur = cur[ dir ]; +\t} while ( cur && cur.nodeType !== 1 ); - return cur; +\treturn cur; } jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.merge( [], elem.childNodes ); - } +\tparent: function( elem ) { +\t\tvar parent = elem.parentNode; +\t\treturn parent && parent.nodeType !== 11 ? parent : null; +\t}, +\tparents: function( elem ) { +\t\treturn jQuery.dir( elem, "parentNode" ); +\t}, +\tparentsUntil: function( elem, i, until ) { +\t\treturn jQuery.dir( elem, "parentNode", until ); +\t}, +\tnext: function( elem ) { +\t\treturn sibling( elem, "nextSibling" ); +\t}, +\tprev: function( elem ) { +\t\treturn sibling( elem, "previousSibling" ); +\t}, +\tnextAll: function( elem ) { +\t\treturn jQuery.dir( elem, "nextSibling" ); +\t}, +\tprevAll: function( elem ) { +\t\treturn jQuery.dir( elem, "previousSibling" ); +\t}, +\tnextUntil: function( elem, i, until ) { +\t\treturn jQuery.dir( elem, "nextSibling", until ); +\t}, +\tprevUntil: function( elem, i, until ) { +\t\treturn jQuery.dir( elem, "previousSibling", until ); +\t}, +\tsiblings: function( elem ) { +\t\treturn jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); +\t}, +\tchildren: function( elem ) { +\t\treturn jQuery.sibling( elem.firstChild ); +\t}, +\tcontents: function( elem ) { +\t\treturn jQuery.nodeName( elem, "iframe" ) ? +\t\t\telem.contentDocument || elem.contentWindow.document : +\t\t\tjQuery.merge( [], elem.childNodes ); +\t} }, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); +\tjQuery.fn[ name ] = function( until, selector ) { +\t\tvar ret = jQuery.map( this, fn, until ); - if ( !runtil.test( name ) ) { - selector = until; - } +\t\tif ( !runtil.test( name ) ) { +\t\t\tselector = until; +\t\t} - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } +\t\tif ( selector && typeof selector === "string" ) { +\t\t\tret = jQuery.filter( selector, ret ); +\t\t} - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; +\t\tret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - if ( this.length > 1 && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } +\t\tif ( this.length > 1 && rparentsprev.test( name ) ) { +\t\t\tret = ret.reverse(); +\t\t} - return this.pushStack( ret ); - }; +\t\treturn this.pushStack( ret ); +\t}; }); jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } +\tfilter: function( expr, elems, not ) { +\t\tif ( not ) { +\t\t\texpr = ":not(" + expr + ")"; +\t\t} + +\t\treturn elems.length === 1 ? +\t\t\tjQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : +\t\t\tjQuery.find.matches(expr, elems); +\t}, + +\tdir: function( elem, dir, until ) { +\t\tvar matched = [], +\t\t\tcur = elem[ dir ]; + +\t\twhile ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { +\t\t\tif ( cur.nodeType === 1 ) { +\t\t\t\tmatched.push( cur ); +\t\t\t} +\t\t\tcur = cur[dir]; +\t\t} +\t\treturn matched; +\t}, + +\tsibling: function( n, elem ) { +\t\tvar r = []; + +\t\tfor ( ; n; n = n.nextSibling ) { +\t\t\tif ( n.nodeType === 1 && n !== elem ) { +\t\t\t\tr.push( n ); +\t\t\t} +\t\t} + +\t\treturn r; +\t} }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem ) { - return ( elem === qualifier ) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; - }); +\t// Can't pass null or undefined to indexOf in Firefox 4 +\t// Set to 0 to skip string check +\tqualifier = qualifier || 0; + +\tif ( jQuery.isFunction( qualifier ) ) { +\t\treturn jQuery.grep(elements, function( elem, i ) { +\t\t\tvar retVal = !!qualifier.call( elem, i, elem ); +\t\t\treturn retVal === keep; +\t\t}); + +\t} else if ( qualifier.nodeType ) { +\t\treturn jQuery.grep(elements, function( elem ) { +\t\t\treturn ( elem === qualifier ) === keep; +\t\t}); + +\t} else if ( typeof qualifier === "string" ) { +\t\tvar filtered = jQuery.grep(elements, function( elem ) { +\t\t\treturn elem.nodeType === 1; +\t\t}); + +\t\tif ( isSimple.test( qualifier ) ) { +\t\t\treturn jQuery.filter(qualifier, filtered, !keep); +\t\t} else { +\t\t\tqualifier = jQuery.filter( qualifier, filtered ); +\t\t} +\t} + +\treturn jQuery.grep(elements, function( elem ) { +\t\treturn ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; +\t}); } function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; +\tvar list = nodeNames.split( "|" ), +\t\tsafeFrag = document.createDocumentFragment(); + +\tif ( safeFrag.createElement ) { +\t\twhile ( list.length ) { +\t\t\tsafeFrag.createElement( +\t\t\t\tlist.pop() +\t\t\t); +\t\t} +\t} +\treturn safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, - rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, - rtagName = /<([\w:]+)/, - rtbody = /\s*$/g, - - // We have to close these tags to support XHTML (#13200) - wrapMap = { - option: [ 1, "" ], - legend: [ 1, "
          ", "
          " ], - area: [ 1, "", "" ], - param: [ 1, "", "" ], - thead: [ 1, "", "
          " ], - tr: [ 2, "", "
          " ], - col: [ 2, "", "
          " ], - td: [ 3, "", "
          " ], - - // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, - // unless wrapped in a div with non-breaking characters in front of it. - _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
          ", "
          " ] - }, - safeFragment = createSafeFragment( document ), - fragmentDiv = safeFragment.appendChild( document.createElement("div") ); +\t\t"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", +\trinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, +\trnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), +\trleadingWhitespace = /^\s+/, +\trxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, +\trtagName = /<([\w:]+)/, +\trtbody = /\s*$/g, + +\t// We have to close these tags to support XHTML (#13200) +\twrapMap = { +\t\toption: [ 1, "" ], +\t\tlegend: [ 1, "
          ", "
          " ], +\t\tarea: [ 1, "", "" ], +\t\tparam: [ 1, "", "" ], +\t\tthead: [ 1, "", "
          " ], +\t\ttr: [ 2, "", "
          " ], +\t\tcol: [ 2, "", "
          " ], +\t\ttd: [ 3, "", "
          " ], + +\t\t// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, +\t\t// unless wrapped in a div with non-breaking characters in front of it. +\t\t_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
          ", "
          " ] +\t}, +\tsafeFragment = createSafeFragment( document ), +\tfragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ - text: function( value ) { - return jQuery.access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); - }, null, value, arguments.length ); - }, - - wrapAll: function( html ) { - if ( jQuery.isFunction( html ) ) { - return this.each(function(i) { - jQuery(this).wrapAll( html.call(this, i) ); - }); - } - - if ( this[0] ) { - // The elements to wrap the target around - var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); - - if ( this[0].parentNode ) { - wrap.insertBefore( this[0] ); - } - - wrap.map(function() { - var elem = this; - - while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { - elem = elem.firstChild; - } - - return elem; - }).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( jQuery.isFunction( html ) ) { - return this.each(function(i) { - jQuery(this).wrapInner( html.call(this, i) ); - }); - } - - return this.each(function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - }); - }, - - wrap: function( html ) { - var isFunction = jQuery.isFunction( html ); - - return this.each(function(i) { - jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); - }); - }, - - unwrap: function() { - return this.parent().each(function() { - if ( !jQuery.nodeName( this, "body" ) ) { - jQuery( this ).replaceWith( this.childNodes ); - } - }).end(); - }, - - append: function() { - return this.domManip(arguments, true, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.appendChild( elem ); - } - }); - }, - - prepend: function() { - return this.domManip(arguments, true, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.insertBefore( elem, this.firstChild ); - } - }); - }, - - before: function() { - return this.domManip( arguments, false, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - }); - }, - - after: function() { - return this.domManip( arguments, false, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - }); - }, - - // keepData is for internal use only--do not document - remove: function( selector, keepData ) { - var elem, - i = 0; - - for ( ; (elem = this[i]) != null; i++ ) { - if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { - if ( !keepData && elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem ) ); - } - - if ( elem.parentNode ) { - if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { - setGlobalEval( getAll( elem, "script" ) ); - } - elem.parentNode.removeChild( elem ); - } - } - } - - return this; - }, - - empty: function() { - var elem, - i = 0; - - for ( ; (elem = this[i]) != null; i++ ) { - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - } - - // Remove any remaining nodes - while ( elem.firstChild ) { - elem.removeChild( elem.firstChild ); - } - - // If this is a select, ensure that it displays empty (#12336) - // Support: IE<9 - if ( elem.options && jQuery.nodeName( elem, "select" ) ) { - elem.options.length = 0; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function () { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - }); - }, - - html: function( value ) { - return jQuery.access( this, function( value ) { - var elem = this[0] || {}, - i = 0, - l = this.length; - - if ( value === undefined ) { - return elem.nodeType === 1 ? - elem.innerHTML.replace( rinlinejQuery, "" ) : - undefined; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && - ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && - !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { - - value = value.replace( rxhtmlTag, "<$1>" ); - - try { - for (; i < l; i++ ) { - // Remove element nodes and prevent memory leaks - elem = this[i] || {}; - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch(e) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function( value ) { - var isFunc = jQuery.isFunction( value ); - - // Make sure that the elements are removed from the DOM before they are inserted - // this can help fix replacing a parent with child elements - if ( !isFunc && typeof value !== "string" ) { - value = jQuery( value ).not( this ).detach(); - } - - return this.domManip( [ value ], true, function( elem ) { - var next = this.nextSibling, - parent = this.parentNode; - - if ( parent ) { - jQuery( this ).remove(); - parent.insertBefore( elem, next ); - } - }); - }, - - detach: function( selector ) { - return this.remove( selector, true ); - }, - - domManip: function( args, table, callback ) { - - // Flatten any nested arrays - args = core_concat.apply( [], args ); - - var first, node, hasScripts, - scripts, doc, fragment, - i = 0, - l = this.length, - set = this, - iNoClone = l - 1, - value = args[0], - isFunction = jQuery.isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { - return this.each(function( index ) { - var self = set.eq( index ); - if ( isFunction ) { - args[0] = value.call( this, index, table ? self.html() : undefined ); - } - self.domManip( args, table, callback ); - }); - } - - if ( l ) { - fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - if ( first ) { - table = table && jQuery.nodeName( first, "tr" ); - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( - table && jQuery.nodeName( this[i], "table" ) ? - findOrAppend( this[i], "tbody" ) : - this[i], - node, - i - ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { - - if ( node.src ) { - // Hope ajax is available... - jQuery.ajax({ - url: node.src, - type: "GET", - dataType: "script", - async: false, - global: false, - "throws": true - }); - } else { - jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); - } - } - } - } - - // Fix #11809: Avoid leaking memory - fragment = first = null; - } - } - - return this; - } +\ttext: function( value ) { +\t\treturn jQuery.access( this, function( value ) { +\t\t\treturn value === undefined ? +\t\t\t\tjQuery.text( this ) : +\t\t\t\tthis.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); +\t\t}, null, value, arguments.length ); +\t}, + +\twrapAll: function( html ) { +\t\tif ( jQuery.isFunction( html ) ) { +\t\t\treturn this.each(function(i) { +\t\t\t\tjQuery(this).wrapAll( html.call(this, i) ); +\t\t\t}); +\t\t} + +\t\tif ( this[0] ) { +\t\t\t// The elements to wrap the target around +\t\t\tvar wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + +\t\t\tif ( this[0].parentNode ) { +\t\t\t\twrap.insertBefore( this[0] ); +\t\t\t} + +\t\t\twrap.map(function() { +\t\t\t\tvar elem = this; + +\t\t\t\twhile ( elem.firstChild && elem.firstChild.nodeType === 1 ) { +\t\t\t\t\telem = elem.firstChild; +\t\t\t\t} + +\t\t\t\treturn elem; +\t\t\t}).append( this ); +\t\t} + +\t\treturn this; +\t}, + +\twrapInner: function( html ) { +\t\tif ( jQuery.isFunction( html ) ) { +\t\t\treturn this.each(function(i) { +\t\t\t\tjQuery(this).wrapInner( html.call(this, i) ); +\t\t\t}); +\t\t} + +\t\treturn this.each(function() { +\t\t\tvar self = jQuery( this ), +\t\t\t\tcontents = self.contents(); + +\t\t\tif ( contents.length ) { +\t\t\t\tcontents.wrapAll( html ); + +\t\t\t} else { +\t\t\t\tself.append( html ); +\t\t\t} +\t\t}); +\t}, + +\twrap: function( html ) { +\t\tvar isFunction = jQuery.isFunction( html ); + +\t\treturn this.each(function(i) { +\t\t\tjQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); +\t\t}); +\t}, + +\tunwrap: function() { +\t\treturn this.parent().each(function() { +\t\t\tif ( !jQuery.nodeName( this, "body" ) ) { +\t\t\t\tjQuery( this ).replaceWith( this.childNodes ); +\t\t\t} +\t\t}).end(); +\t}, + +\tappend: function() { +\t\treturn this.domManip(arguments, true, function( elem ) { +\t\t\tif ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { +\t\t\t\tthis.appendChild( elem ); +\t\t\t} +\t\t}); +\t}, + +\tprepend: function() { +\t\treturn this.domManip(arguments, true, function( elem ) { +\t\t\tif ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { +\t\t\t\tthis.insertBefore( elem, this.firstChild ); +\t\t\t} +\t\t}); +\t}, + +\tbefore: function() { +\t\treturn this.domManip( arguments, false, function( elem ) { +\t\t\tif ( this.parentNode ) { +\t\t\t\tthis.parentNode.insertBefore( elem, this ); +\t\t\t} +\t\t}); +\t}, + +\tafter: function() { +\t\treturn this.domManip( arguments, false, function( elem ) { +\t\t\tif ( this.parentNode ) { +\t\t\t\tthis.parentNode.insertBefore( elem, this.nextSibling ); +\t\t\t} +\t\t}); +\t}, + +\t// keepData is for internal use only--do not document +\tremove: function( selector, keepData ) { +\t\tvar elem, +\t\t\ti = 0; + +\t\tfor ( ; (elem = this[i]) != null; i++ ) { +\t\t\tif ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { +\t\t\t\tif ( !keepData && elem.nodeType === 1 ) { +\t\t\t\t\tjQuery.cleanData( getAll( elem ) ); +\t\t\t\t} + +\t\t\t\tif ( elem.parentNode ) { +\t\t\t\t\tif ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { +\t\t\t\t\t\tsetGlobalEval( getAll( elem, "script" ) ); +\t\t\t\t\t} +\t\t\t\t\telem.parentNode.removeChild( elem ); +\t\t\t\t} +\t\t\t} +\t\t} + +\t\treturn this; +\t}, + +\tempty: function() { +\t\tvar elem, +\t\t\ti = 0; + +\t\tfor ( ; (elem = this[i]) != null; i++ ) { +\t\t\t// Remove element nodes and prevent memory leaks +\t\t\tif ( elem.nodeType === 1 ) { +\t\t\t\tjQuery.cleanData( getAll( elem, false ) ); +\t\t\t} + +\t\t\t// Remove any remaining nodes +\t\t\twhile ( elem.firstChild ) { +\t\t\t\telem.removeChild( elem.firstChild ); +\t\t\t} + +\t\t\t// If this is a select, ensure that it displays empty (#12336) +\t\t\t// Support: IE<9 +\t\t\tif ( elem.options && jQuery.nodeName( elem, "select" ) ) { +\t\t\t\telem.options.length = 0; +\t\t\t} +\t\t} + +\t\treturn this; +\t}, + +\tclone: function( dataAndEvents, deepDataAndEvents ) { +\t\tdataAndEvents = dataAndEvents == null ? false : dataAndEvents; +\t\tdeepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + +\t\treturn this.map( function () { +\t\t\treturn jQuery.clone( this, dataAndEvents, deepDataAndEvents ); +\t\t}); +\t}, + +\thtml: function( value ) { +\t\treturn jQuery.access( this, function( value ) { +\t\t\tvar elem = this[0] || {}, +\t\t\t\ti = 0, +\t\t\t\tl = this.length; + +\t\t\tif ( value === undefined ) { +\t\t\t\treturn elem.nodeType === 1 ? +\t\t\t\t\telem.innerHTML.replace( rinlinejQuery, "" ) : +\t\t\t\t\tundefined; +\t\t\t} + +\t\t\t// See if we can take a shortcut and just use innerHTML +\t\t\tif ( typeof value === "string" && !rnoInnerhtml.test( value ) && +\t\t\t\t( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && +\t\t\t\t( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && +\t\t\t\t!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + +\t\t\t\tvalue = value.replace( rxhtmlTag, "<$1>" ); + +\t\t\t\ttry { +\t\t\t\t\tfor (; i < l; i++ ) { +\t\t\t\t\t\t// Remove element nodes and prevent memory leaks +\t\t\t\t\t\telem = this[i] || {}; +\t\t\t\t\t\tif ( elem.nodeType === 1 ) { +\t\t\t\t\t\t\tjQuery.cleanData( getAll( elem, false ) ); +\t\t\t\t\t\t\telem.innerHTML = value; +\t\t\t\t\t\t} +\t\t\t\t\t} + +\t\t\t\t\telem = 0; + +\t\t\t\t// If using innerHTML throws an exception, use the fallback method +\t\t\t\t} catch(e) {} +\t\t\t} + +\t\t\tif ( elem ) { +\t\t\t\tthis.empty().append( value ); +\t\t\t} +\t\t}, null, value, arguments.length ); +\t}, + +\treplaceWith: function( value ) { +\t\tvar isFunc = jQuery.isFunction( value ); + +\t\t// Make sure that the elements are removed from the DOM before they are inserted +\t\t// this can help fix replacing a parent with child elements +\t\tif ( !isFunc && typeof value !== "string" ) { +\t\t\tvalue = jQuery( value ).not( this ).detach(); +\t\t} + +\t\treturn this.domManip( [ value ], true, function( elem ) { +\t\t\tvar next = this.nextSibling, +\t\t\t\tparent = this.parentNode; + +\t\t\tif ( parent ) { +\t\t\t\tjQuery( this ).remove(); +\t\t\t\tparent.insertBefore( elem, next ); +\t\t\t} +\t\t}); +\t}, + +\tdetach: function( selector ) { +\t\treturn this.remove( selector, true ); +\t}, + +\tdomManip: function( args, table, callback ) { + +\t\t// Flatten any nested arrays +\t\targs = core_concat.apply( [], args ); + +\t\tvar first, node, hasScripts, +\t\t\tscripts, doc, fragment, +\t\t\ti = 0, +\t\t\tl = this.length, +\t\t\tset = this, +\t\t\tiNoClone = l - 1, +\t\t\tvalue = args[0], +\t\t\tisFunction = jQuery.isFunction( value ); + +\t\t// We can't cloneNode fragments that contain checked, in WebKit +\t\tif ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { +\t\t\treturn this.each(function( index ) { +\t\t\t\tvar self = set.eq( index ); +\t\t\t\tif ( isFunction ) { +\t\t\t\t\targs[0] = value.call( this, index, table ? self.html() : undefined ); +\t\t\t\t} +\t\t\t\tself.domManip( args, table, callback ); +\t\t\t}); +\t\t} + +\t\tif ( l ) { +\t\t\tfragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); +\t\t\tfirst = fragment.firstChild; + +\t\t\tif ( fragment.childNodes.length === 1 ) { +\t\t\t\tfragment = first; +\t\t\t} + +\t\t\tif ( first ) { +\t\t\t\ttable = table && jQuery.nodeName( first, "tr" ); +\t\t\t\tscripts = jQuery.map( getAll( fragment, "script" ), disableScript ); +\t\t\t\thasScripts = scripts.length; + +\t\t\t\t// Use the original fragment for the last item instead of the first because it can end up +\t\t\t\t// being emptied incorrectly in certain situations (#8070). +\t\t\t\tfor ( ; i < l; i++ ) { +\t\t\t\t\tnode = fragment; + +\t\t\t\t\tif ( i !== iNoClone ) { +\t\t\t\t\t\tnode = jQuery.clone( node, true, true ); + +\t\t\t\t\t\t// Keep references to cloned scripts for later restoration +\t\t\t\t\t\tif ( hasScripts ) { +\t\t\t\t\t\t\tjQuery.merge( scripts, getAll( node, "script" ) ); +\t\t\t\t\t\t} +\t\t\t\t\t} + +\t\t\t\t\tcallback.call( +\t\t\t\t\t\ttable && jQuery.nodeName( this[i], "table" ) ? +\t\t\t\t\t\t\tfindOrAppend( this[i], "tbody" ) : +\t\t\t\t\t\t\tthis[i], +\t\t\t\t\t\tnode, +\t\t\t\t\t\ti +\t\t\t\t\t); +\t\t\t\t} + +\t\t\t\tif ( hasScripts ) { +\t\t\t\t\tdoc = scripts[ scripts.length - 1 ].ownerDocument; + +\t\t\t\t\t// Reenable scripts +\t\t\t\t\tjQuery.map( scripts, restoreScript ); + +\t\t\t\t\t// Evaluate executable scripts on first document insertion +\t\t\t\t\tfor ( i = 0; i < hasScripts; i++ ) { +\t\t\t\t\t\tnode = scripts[ i ]; +\t\t\t\t\t\tif ( rscriptType.test( node.type || "" ) && +\t\t\t\t\t\t\t!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + +\t\t\t\t\t\t\tif ( node.src ) { +\t\t\t\t\t\t\t\t// Hope ajax is available... +\t\t\t\t\t\t\t\tjQuery.ajax({ +\t\t\t\t\t\t\t\t\turl: node.src, +\t\t\t\t\t\t\t\t\ttype: "GET", +\t\t\t\t\t\t\t\t\tdataType: "script", +\t\t\t\t\t\t\t\t\tasync: false, +\t\t\t\t\t\t\t\t\tglobal: false, +\t\t\t\t\t\t\t\t\t"throws": true +\t\t\t\t\t\t\t\t}); +\t\t\t\t\t\t\t} else { +\t\t\t\t\t\t\t\tjQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} +\t\t\t\t\t} +\t\t\t\t} + +\t\t\t\t// Fix #11809: Avoid leaking memory +\t\t\t\tfragment = first = null; +\t\t\t} +\t\t} + +\t\treturn this; +\t} }); function findOrAppend( elem, tag ) { - return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +\treturn elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { - var attr = elem.getAttributeNode("type"); - elem.type = ( attr && attr.specified ) + "/" + elem.type; - return elem; +\tvar attr = elem.getAttributeNode("type"); +\telem.type = ( attr && attr.specified ) + "/" + elem.type; +\treturn elem; } function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - if ( match ) { - elem.type = match[1]; - } else { - elem.removeAttribute("type"); - } - return elem; +\tvar match = rscriptTypeMasked.exec( elem.type ); +\tif ( match ) { +\t\telem.type = match[1]; +\t} else { +\t\telem.removeAttribute("type"); +\t} +\treturn elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { - var elem, - i = 0; - for ( ; (elem = elems[i]) != null; i++ ) { - jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); - } +\tvar elem, +\t\ti = 0; +\tfor ( ; (elem = elems[i]) != null; i++ ) { +\t\tjQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); +\t} } function cloneCopyEvent( src, dest ) { - if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { - return; - } - - var type, i, l, - oldData = jQuery._data( src ), - curData = jQuery._data( dest, oldData ), - events = oldData.events; - - if ( events ) { - delete curData.handle; - curData.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - - // make the cloned public data object a copy from the original - if ( curData.data ) { - curData.data = jQuery.extend( {}, curData.data ); - } +\tif ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { +\t\treturn; +\t} + +\tvar type, i, l, +\t\toldData = jQuery._data( src ), +\t\tcurData = jQuery._data( dest, oldData ), +\t\tevents = oldData.events; + +\tif ( events ) { +\t\tdelete curData.handle; +\t\tcurData.events = {}; + +\t\tfor ( type in events ) { +\t\t\tfor ( i = 0, l = events[ type ].length; i < l; i++ ) { +\t\t\t\tjQuery.event.add( dest, type, events[ type ][ i ] ); +\t\t\t} +\t\t} +\t} + +\t// make the cloned public data object a copy from the original +\tif ( curData.data ) { +\t\tcurData.data = jQuery.extend( {}, curData.data ); +\t} } function fixCloneNodeIssues( src, dest ) { - var nodeName, e, data; - - // We do not need to do anything for non-Elements - if ( dest.nodeType !== 1 ) { - return; - } - - nodeName = dest.nodeName.toLowerCase(); - - // IE6-8 copies events bound via attachEvent when using cloneNode. - if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { - data = jQuery._data( dest ); - - for ( e in data.events ) { - jQuery.removeEvent( dest, e, data.handle ); - } - - // Event data gets referenced instead of copied if the expando gets copied too - dest.removeAttribute( jQuery.expando ); - } - - // IE blanks contents when cloning scripts, and tries to evaluate newly-set text - if ( nodeName === "script" && dest.text !== src.text ) { - disableScript( dest ).text = src.text; - restoreScript( dest ); - - // IE6-10 improperly clones children of object elements using classid. - // IE10 throws NoModificationAllowedError if parent is null, #12132. - } else if ( nodeName === "object" ) { - if ( dest.parentNode ) { - dest.outerHTML = src.outerHTML; - } - - // This path appears unavoidable for IE9. When cloning an object - // element in IE9, the outerHTML strategy above is not sufficient. - // If the src has innerHTML and the destination does not, - // copy the src.innerHTML into the dest.innerHTML. #10324 - if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { - dest.innerHTML = src.innerHTML; - } - - } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { - // IE6-8 fails to persist the checked state of a cloned checkbox - // or radio button. Worse, IE6-7 fail to give the cloned element - // a checked appearance if the defaultChecked value isn't also set - - dest.defaultChecked = dest.checked = src.checked; - - // IE6-7 get confused and end up setting the value of a cloned - // checkbox/radio button to an empty string instead of "on" - if ( dest.value !== src.value ) { - dest.value = src.value; - } - - // IE6-8 fails to return the selected option to the default selected - // state when cloning options - } else if ( nodeName === "option" ) { - dest.defaultSelected = dest.selected = src.defaultSelected; - - // IE6-8 fails to set the defaultValue to the correct value when - // cloning other types of input fields - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } +\tvar nodeName, e, data; + +\t// We do not need to do anything for non-Elements +\tif ( dest.nodeType !== 1 ) { +\t\treturn; +\t} + +\tnodeName = dest.nodeName.toLowerCase(); + +\t// IE6-8 copies events bound via attachEvent when using cloneNode. +\tif ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { +\t\tdata = jQuery._data( dest ); + +\t\tfor ( e in data.events ) { +\t\t\tjQuery.removeEvent( dest, e, data.handle ); +\t\t} + +\t\t// Event data gets referenced instead of copied if the expando gets copied too +\t\tdest.removeAttribute( jQuery.expando ); +\t} + +\t// IE blanks contents when cloning scripts, and tries to evaluate newly-set text +\tif ( nodeName === "script" && dest.text !== src.text ) { +\t\tdisableScript( dest ).text = src.text; +\t\trestoreScript( dest ); + +\t// IE6-10 improperly clones children of object elements using classid. +\t// IE10 throws NoModificationAllowedError if parent is null, #12132. +\t} else if ( nodeName === "object" ) { +\t\tif ( dest.parentNode ) { +\t\t\tdest.outerHTML = src.outerHTML; +\t\t} + +\t\t// This path appears unavoidable for IE9. When cloning an object +\t\t// element in IE9, the outerHTML strategy above is not sufficient. +\t\t// If the src has innerHTML and the destination does not, +\t\t// copy the src.innerHTML into the dest.innerHTML. #10324 +\t\tif ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { +\t\t\tdest.innerHTML = src.innerHTML; +\t\t} + +\t} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { +\t\t// IE6-8 fails to persist the checked state of a cloned checkbox +\t\t// or radio button. Worse, IE6-7 fail to give the cloned element +\t\t// a checked appearance if the defaultChecked value isn't also set + +\t\tdest.defaultChecked = dest.checked = src.checked; + +\t\t// IE6-7 get confused and end up setting the value of a cloned +\t\t// checkbox/radio button to an empty string instead of "on" +\t\tif ( dest.value !== src.value ) { +\t\t\tdest.value = src.value; +\t\t} + +\t// IE6-8 fails to return the selected option to the default selected +\t// state when cloning options +\t} else if ( nodeName === "option" ) { +\t\tdest.defaultSelected = dest.selected = src.defaultSelected; + +\t// IE6-8 fails to set the defaultValue to the correct value when +\t// cloning other types of input fields +\t} else if ( nodeName === "input" || nodeName === "textarea" ) { +\t\tdest.defaultValue = src.defaultValue; +\t} } jQuery.each({ - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" +\tappendTo: "append", +\tprependTo: "prepend", +\tinsertBefore: "before", +\tinsertAfter: "after", +\treplaceAll: "replaceWith" }, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - i = 0, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone(true); - jQuery( insert[i] )[ original ]( elems ); - - // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() - core_push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; +\tjQuery.fn[ name ] = function( selector ) { +\t\tvar elems, +\t\t\ti = 0, +\t\t\tret = [], +\t\t\tinsert = jQuery( selector ), +\t\t\tlast = insert.length - 1; + +\t\tfor ( ; i <= last; i++ ) { +\t\t\telems = i === last ? this : this.clone(true); +\t\t\tjQuery( insert[i] )[ original ]( elems ); + +\t\t\t// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() +\t\t\tcore_push.apply( ret, elems.get() ); +\t\t} + +\t\treturn this.pushStack( ret ); +\t}; }); function getAll( context, tag ) { - var elems, elem, - i = 0, - found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : - typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : - undefined; - - if ( !found ) { - for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { - if ( !tag || jQuery.nodeName( elem, tag ) ) { - found.push( elem ); - } else { - jQuery.merge( found, getAll( elem, tag ) ); - } - } - } - - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], found ) : - found; +\tvar elems, elem, +\t\ti = 0, +\t\tfound = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : +\t\t\ttypeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : +\t\t\tundefined; + +\tif ( !found ) { +\t\tfor ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { +\t\t\tif ( !tag || jQuery.nodeName( elem, tag ) ) { +\t\t\t\tfound.push( elem ); +\t\t\t} else { +\t\t\t\tjQuery.merge( found, getAll( elem, tag ) ); +\t\t\t} +\t\t} +\t} + +\treturn tag === undefined || tag && jQuery.nodeName( context, tag ) ? +\t\tjQuery.merge( [ context ], found ) : +\t\tfound; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { - if ( manipulation_rcheckableType.test( elem.type ) ) { - elem.defaultChecked = elem.checked; - } +\tif ( manipulation_rcheckableType.test( elem.type ) ) { +\t\telem.defaultChecked = elem.checked; +\t} } jQuery.extend({ - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var destElements, node, clone, i, srcElements, - inPage = jQuery.contains( elem.ownerDocument, elem ); - - if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { - clone = elem.cloneNode( true ); - - // IE<=8 does not properly clone detached, unknown element nodes - } else { - fragmentDiv.innerHTML = elem.outerHTML; - fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); - } - - if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && - (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { - - // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - // Fix all IE cloning issues - for ( i = 0; (node = srcElements[i]) != null; ++i ) { - // Ensure that the destination node is not null; Fixes #9587 - if ( destElements[i] ) { - fixCloneNodeIssues( node, destElements[i] ); - } - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0; (node = srcElements[i]) != null; i++ ) { - cloneCopyEvent( node, destElements[i] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - destElements = srcElements = node = null; - - // Return the cloned set - return clone; - }, - - buildFragment: function( elems, context, scripts, selection ) { - var j, elem, contains, - tmp, tag, tbody, wrap, - l = elems.length, - - // Ensure a safe fragment - safe = createSafeFragment( context ), - - nodes = [], - i = 0; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || safe.appendChild( context.createElement("div") ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - - tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; - - // Descend through wrappers to the right content - j = wrap[0]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Manually add leading whitespace removed by IE - if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { - nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); - } - - // Remove IE's autoinserted from table fragments - if ( !jQuery.support.tbody ) { - - // String was a , *may* have spurious - elem = tag === "table" && !rtbody.test( elem ) ? - tmp.firstChild : - - // String was a bare or - wrap[1] === "
          " && !rtbody.test( elem ) ? - tmp : - 0; - - j = elem && elem.childNodes.length; - while ( j-- ) { - if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { - elem.removeChild( tbody ); - } - } - } - - jQuery.merge( nodes, tmp.childNodes ); - - // Fix #12392 for WebKit and IE > 9 - tmp.textContent = ""; - - // Fix #12392 for oldIE - while ( tmp.firstChild ) { - tmp.removeChild( tmp.firstChild ); - } - - // Remember the top-level container for proper cleanup - tmp = safe.lastChild; - } - } - } - - // Fix #11356: Clear elements from fragment - if ( tmp ) { - safe.removeChild( tmp ); - } - - // Reset defaultChecked for any radios and checkboxes - // about to be appended to the DOM in IE 6/7 (#8060) - if ( !jQuery.support.appendChecked ) { - jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); - } - - i = 0; - while ( (elem = nodes[ i++ ]) ) { - - // #4087 - If origin and destination elements are the same, and this is - // that element, do not do anything - if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( safe.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( (elem = tmp[ j++ ]) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - tmp = null; - - return safe; - }, - - cleanData: function( elems, /* internal */ acceptData ) { - var elem, type, id, data, - i = 0, - internalKey = jQuery.expando, - cache = jQuery.cache, - deleteExpando = jQuery.support.deleteExpando, - special = jQuery.event.special; - - for ( ; (elem = elems[i]) != null; i++ ) { - - if ( acceptData || jQuery.acceptData( elem ) ) { - - id = elem[ internalKey ]; - data = id && cache[ id ]; - - if ( data ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Remove cache only if it was not already removed by jQuery.event.remove - if ( cache[ id ] ) { - - delete cache[ id ]; - - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( deleteExpando ) { - delete elem[ internalKey ]; - - } else if ( typeof elem.removeAttribute !== core_strundefined ) { - elem.removeAttribute( internalKey ); - - } else { - elem[ internalKey ] = null; - } - - core_deletedIds.push( id ); - } - } - } - } - } +\tclone: function( elem, dataAndEvents, deepDataAndEvents ) { +\t\tvar destElements, node, clone, i, srcElements, +\t\t\tinPage = jQuery.contains( elem.ownerDocument, elem ); + +\t\tif ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { +\t\t\tclone = elem.cloneNode( true ); + +\t\t// IE<=8 does not properly clone detached, unknown element nodes +\t\t} else { +\t\t\tfragmentDiv.innerHTML = elem.outerHTML; +\t\t\tfragmentDiv.removeChild( clone = fragmentDiv.firstChild ); +\t\t} + +\t\tif ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && +\t\t\t\t(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + +\t\t\t// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 +\t\t\tdestElements = getAll( clone ); +\t\t\tsrcElements = getAll( elem ); + +\t\t\t// Fix all IE cloning issues +\t\t\tfor ( i = 0; (node = srcElements[i]) != null; ++i ) { +\t\t\t\t// Ensure that the destination node is not null; Fixes #9587 +\t\t\t\tif ( destElements[i] ) { +\t\t\t\t\tfixCloneNodeIssues( node, destElements[i] ); +\t\t\t\t} +\t\t\t} +\t\t} + +\t\t// Copy the events from the original to the clone +\t\tif ( dataAndEvents ) { +\t\t\tif ( deepDataAndEvents ) { +\t\t\t\tsrcElements = srcElements || getAll( elem ); +\t\t\t\tdestElements = destElements || getAll( clone ); + +\t\t\t\tfor ( i = 0; (node = srcElements[i]) != null; i++ ) { +\t\t\t\t\tcloneCopyEvent( node, destElements[i] ); +\t\t\t\t} +\t\t\t} else { +\t\t\t\tcloneCopyEvent( elem, clone ); +\t\t\t} +\t\t} + +\t\t// Preserve script evaluation history +\t\tdestElements = getAll( clone, "script" ); +\t\tif ( destElements.length > 0 ) { +\t\t\tsetGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); +\t\t} + +\t\tdestElements = srcElements = node = null; + +\t\t// Return the cloned set +\t\treturn clone; +\t}, + +\tbuildFragment: function( elems, context, scripts, selection ) { +\t\tvar j, elem, contains, +\t\t\ttmp, tag, tbody, wrap, +\t\t\tl = elems.length, + +\t\t\t// Ensure a safe fragment +\t\t\tsafe = createSafeFragment( context ), + +\t\t\tnodes = [], +\t\t\ti = 0; + +\t\tfor ( ; i < l; i++ ) { +\t\t\telem = elems[ i ]; + +\t\t\tif ( elem || elem === 0 ) { + +\t\t\t\t// Add nodes directly +\t\t\t\tif ( jQuery.type( elem ) === "object" ) { +\t\t\t\t\tjQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + +\t\t\t\t// Convert non-html into a text node +\t\t\t\t} else if ( !rhtml.test( elem ) ) { +\t\t\t\t\tnodes.push( context.createTextNode( elem ) ); + +\t\t\t\t// Convert html into DOM nodes +\t\t\t\t} else { +\t\t\t\t\ttmp = tmp || safe.appendChild( context.createElement("div") ); + +\t\t\t\t\t// Deserialize a standard representation +\t\t\t\t\ttag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); +\t\t\t\t\twrap = wrapMap[ tag ] || wrapMap._default; + +\t\t\t\t\ttmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + +\t\t\t\t\t// Descend through wrappers to the right content +\t\t\t\t\tj = wrap[0]; +\t\t\t\t\twhile ( j-- ) { +\t\t\t\t\t\ttmp = tmp.lastChild; +\t\t\t\t\t} + +\t\t\t\t\t// Manually add leading whitespace removed by IE +\t\t\t\t\tif ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { +\t\t\t\t\t\tnodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); +\t\t\t\t\t} + +\t\t\t\t\t// Remove IE's autoinserted from table fragments +\t\t\t\t\tif ( !jQuery.support.tbody ) { + +\t\t\t\t\t\t// String was a
          , *may* have spurious +\t\t\t\t\t\telem = tag === "table" && !rtbody.test( elem ) ? +\t\t\t\t\t\t\ttmp.firstChild : + +\t\t\t\t\t\t\t// String was a bare or +\t\t\t\t\t\t\twrap[1] === "
          " && !rtbody.test( elem ) ? +\t\t\t\t\t\t\t\ttmp : +\t\t\t\t\t\t\t\t0; + +\t\t\t\t\t\tj = elem && elem.childNodes.length; +\t\t\t\t\t\twhile ( j-- ) { +\t\t\t\t\t\t\tif ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { +\t\t\t\t\t\t\t\telem.removeChild( tbody ); +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} +\t\t\t\t\t} + +\t\t\t\t\tjQuery.merge( nodes, tmp.childNodes ); + +\t\t\t\t\t// Fix #12392 for WebKit and IE > 9 +\t\t\t\t\ttmp.textContent = ""; + +\t\t\t\t\t// Fix #12392 for oldIE +\t\t\t\t\twhile ( tmp.firstChild ) { +\t\t\t\t\t\ttmp.removeChild( tmp.firstChild ); +\t\t\t\t\t} + +\t\t\t\t\t// Remember the top-level container for proper cleanup +\t\t\t\t\ttmp = safe.lastChild; +\t\t\t\t} +\t\t\t} +\t\t} + +\t\t// Fix #11356: Clear elements from fragment +\t\tif ( tmp ) { +\t\t\tsafe.removeChild( tmp ); +\t\t} + +\t\t// Reset defaultChecked for any radios and checkboxes +\t\t// about to be appended to the DOM in IE 6/7 (#8060) +\t\tif ( !jQuery.support.appendChecked ) { +\t\t\tjQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); +\t\t} + +\t\ti = 0; +\t\twhile ( (elem = nodes[ i++ ]) ) { + +\t\t\t// #4087 - If origin and destination elements are the same, and this is +\t\t\t// that element, do not do anything +\t\t\tif ( selection && jQuery.inArray( elem, selection ) !== -1 ) { +\t\t\t\tcontinue; +\t\t\t} + +\t\t\tcontains = jQuery.contains( elem.ownerDocument, elem ); + +\t\t\t// Append to fragment +\t\t\ttmp = getAll( safe.appendChild( elem ), "script" ); + +\t\t\t// Preserve script evaluation history +\t\t\tif ( contains ) { +\t\t\t\tsetGlobalEval( tmp ); +\t\t\t} + +\t\t\t// Capture executables +\t\t\tif ( scripts ) { +\t\t\t\tj = 0; +\t\t\t\twhile ( (elem = tmp[ j++ ]) ) { +\t\t\t\t\tif ( rscriptType.test( elem.type || "" ) ) { +\t\t\t\t\t\tscripts.push( elem ); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} + +\t\ttmp = null; + +\t\treturn safe; +\t}, + +\tcleanData: function( elems, /* internal */ acceptData ) { +\t\tvar elem, type, id, data, +\t\t\ti = 0, +\t\t\tinternalKey = jQuery.expando, +\t\t\tcache = jQuery.cache, +\t\t\tdeleteExpando = jQuery.support.deleteExpando, +\t\t\tspecial = jQuery.event.special; + +\t\tfor ( ; (elem = elems[i]) != null; i++ ) { + +\t\t\tif ( acceptData || jQuery.acceptData( elem ) ) { + +\t\t\t\tid = elem[ internalKey ]; +\t\t\t\tdata = id && cache[ id ]; + +\t\t\t\tif ( data ) { +\t\t\t\t\tif ( data.events ) { +\t\t\t\t\t\tfor ( type in data.events ) { +\t\t\t\t\t\t\tif ( special[ type ] ) { +\t\t\t\t\t\t\t\tjQuery.event.remove( elem, type ); + +\t\t\t\t\t\t\t// This is a shortcut to avoid jQuery.event.remove's overhead +\t\t\t\t\t\t\t} else { +\t\t\t\t\t\t\t\tjQuery.removeEvent( elem, type, data.handle ); +\t\t\t\t\t\t\t} +\t\t\t\t\t\t} +\t\t\t\t\t} + +\t\t\t\t\t// Remove cache only if it was not already removed by jQuery.event.remove +\t\t\t\t\tif ( cache[ id ] ) { + +\t\t\t\t\t\tdelete cache[ id ]; + +\t\t\t\t\t\t// IE does not allow us to delete expando properties from nodes, +\t\t\t\t\t\t// nor does it have a removeAttribute function on Document nodes; +\t\t\t\t\t\t// we must handle all of these cases +\t\t\t\t\t\tif ( deleteExpando ) { +\t\t\t\t\t\t\tdelete elem[ internalKey ]; + +\t\t\t\t\t\t} else if ( typeof elem.removeAttribute !== core_strundefined ) { +\t\t\t\t\t\t\telem.removeAttribute( internalKey ); + +\t\t\t\t\t\t} else { +\t\t\t\t\t\t\telem[ internalKey ] = null; +\t\t\t\t\t\t} + +\t\t\t\t\t\tcore_deletedIds.push( id ); +\t\t\t\t\t} +\t\t\t\t} +\t\t\t} +\t\t} +\t} }); var iframe, getStyles, curCSS, - ralpha = /alpha\([^)]*\)/i, - ropacity = /opacity\s*=\s*([^)]*)/, - rposition = /^(top|right|bottom|left)$/, - // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" - // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rmargin = /^margin/, - rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), - rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), - rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), - elemdisplay = { BODY: "block" }, - - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: 0, - fontWeight: 400 - }, - - cssExpand = [ "Top", "Right", "Bottom", "Left" ], - cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; +\tralpha = /alpha\([^)]*\)/i, +\tropacity = /opacity\s*=\s*([^)]*)/, +\trposition = /^(top|right|bottom|left)$/, +\t// swappable if display is none or starts with table except "table", "table-cell", or "table-caption" +\t// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display +\trdisplayswap = /^(none|table(?!-c[ea]).+)/, +\trmargin = /^margin/, +\trnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), +\trnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), +\trrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), +\telemdisplay = { BODY: "block" }, + +\tcssShow = { position: "absolute", visibility: "hidden", display: "block" }, +\tcssNormalTransform = { +\t\tletterSpacing: 0, +\t\tfontWeight: 400 +\t}, + +\tcssExpand = [ "Top", "Right", "Bottom", "Left" ], +\tcssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { - // shortcut for names that are not vendor prefixed - if ( name in style ) { - return name; - } +\t// shortcut for names that are not vendor prefixed +\tif ( name in style ) { +\t\treturn name; +\t} - // check for vendor prefixed names - var capName = name.charAt(0).toUpperCase() + name.slice(1), - origName = name, - i = cssPrefixes.length; +\t// check for vendor prefixed names +\tvar capName = name.charAt(0).toUpperCase() + name.slice(1), +\t\torigName = name, +\t\ti = cssPrefixes.length; - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in style ) { - return name; - } - } +\twhile ( i-- ) { +\t\tname = cssPrefixes[ i ] + capName; +\t\tif ( name in style ) { +\t\t\treturn name; +\t\t} +\t} - return origName; +\treturn origName; } function isHidden( elem, el ) { - // isHidden might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +\t// isHidden might be called from jQuery#filter function; +\t// in that case, element will be second argument +\telem = el || elem; +\treturn jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { - var display, elem, hidden, - values = [], - index = 0, - length = elements.length; - - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - values[ index ] = jQuery._data( elem, "olddisplay" ); - display = elem.style.display; - if ( show ) { - // Reset the inline display of this element to learn if it is - // being hidden by cascaded rules or not - if ( !values[ index ] && display === "none" ) { - elem.style.display = ""; - } - - // Set elements which have been overridden with display: none - // in a stylesheet to whatever the default browser style is - // for such an element - if ( elem.style.display === "" && isHidden( elem ) ) { - values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); - } - } else { - - if ( !values[ index ] ) { - hidden = isHidden( elem ); - - if ( display && display !== "none" || !hidden ) { - jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); - } - } - } - } - - // Set the display of most of the elements in a second loop - // to avoid the constant reflow - for ( index = 0; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - if ( !show || elem.style.display === "none" || elem.style.display === "" ) { - elem.style.display = show ? values[ index ] || "" : "none"; - } - } - - return elements; +\tvar display, elem, hidden, +\t\tvalues = [], +\t\tindex = 0, +\t\tlength = elements.length; + +\tfor ( ; index < length; index++ ) { +\t\telem = elements[ index ]; +\t\tif ( !elem.style ) { +\t\t\tcontinue; +\t\t} + +\t\tvalues[ index ] = jQuery._data( elem, "olddisplay" ); +\t\tdisplay = elem.style.display; +\t\tif ( show ) { +\t\t\t// Reset the inline display of this element to learn if it is +\t\t\t// being hidden by cascaded rules or not +\t\t\tif ( !values[ index ] && display === "none" ) { +\t\t\t\telem.style.display = ""; +\t\t\t} + +\t\t\t// Set elements which have been overridden with display: none +\t\t\t// in a stylesheet to whatever the default browser style is +\t\t\t// for such an element +\t\t\tif ( elem.style.display === "" && isHidden( elem ) ) { +\t\t\t\tvalues[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); +\t\t\t} +\t\t} else { + +\t\t\tif ( !values[ index ] ) { +\t\t\t\thidden = isHidden( elem ); + +\t\t\t\tif ( display && display !== "none" || !hidden ) { +\t\t\t\t\tjQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); +\t\t\t\t} +\t\t\t} +\t\t} +\t} + +\t// Set the display of most of the elements in a second loop +\t// to avoid the constant reflow +\tfor ( index = 0; index < length; index++ ) { +\t\telem = elements[ index ]; +\t\tif ( !elem.style ) { +\t\t\tcontinue; +\t\t} +\t\tif ( !show || elem.style.display === "none" || elem.style.display === "" ) { +\t\t\telem.style.display = show ? values[ index ] || "" : "none"; +\t\t} +\t} + +\treturn elements; } jQuery.fn.extend({ - css: function( name, value ) { - return jQuery.access( this, function( elem, name, value ) { - var len, styles, - map = {}, - i = 0; - - if ( jQuery.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - }, - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - var bool = typeof state === "boolean"; - - return this.each(function() { - if ( bool ? state : isHidden( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - }); - } +\tcss: function( name, value ) { +\t\treturn jQuery.access( this, function( elem, name, value ) { +\t\t\tvar len, styles, +\t\t\t\tmap = {}, +\t\t\t\ti = 0; + +\t\t\tif ( jQuery.isArray( name ) ) { +\t\t\t\tstyles = getStyles( elem ); +\t\t\t\tlen = name.length; + +\t\t\t\tfor ( ; i < len; i++ ) { +\t\t\t\t\tmap[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); +\t\t\t\t} + +\t\t\t\treturn map; +\t\t\t} + +\t\t\treturn value !== undefined ? +\t\t\t\tjQuery.style( elem, name, value ) : +\t\t\t\tjQuery.css( elem, name ); +\t\t}, name, value, arguments.length > 1 ); +\t}, +\tshow: function() { +\t\treturn showHide( this, true ); +\t}, +\thide: function() { +\t\treturn showHide( this ); +\t}, +\ttoggle: function( state ) { +\t\tvar bool = typeof state === "boolean"; + +\t\treturn this.each(function() { +\t\t\tif ( bool ? state : isHidden( this ) ) { +\t\t\t\tjQuery( this ).show(); +\t\t\t} else { +\t\t\t\tjQuery( this ).hide(); +\t\t\t} +\t\t}); +\t} }); jQuery.extend({ - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Exclude the following css properties to add px - cssNumber: { - "columnCount": true, - "fillOpacity": true, - "fontWeight": true, - "lineHeight": true, - "opacity": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: { - // normalize float css property - "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" - }, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = jQuery.camelCase( name ), - style = elem.style; - - name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // convert relative number strings (+= or -=) to relative numbers. #7345 - if ( type === "string" && (ret = rrelNum.exec( value )) ) { - value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); - // Fixes bug #9237 - type = "number"; - } - - // Make sure that NaN and null values aren't set. See: #7116 - if ( value == null || type === "number" && isNaN( value ) ) { - return; - } - - // If a number was passed in, add 'px' to the (except for certain CSS properties) - if ( type === "number" && !jQuery.cssNumber[ origName ] ) { - value += "px"; - } - - // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, - // but it would mean to define eight (for every problematic property) identical functions - if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { - - // Wrapped to prevent IE from throwing errors when 'invalid' values are provided - // Fixes bug #5509 - try { - style[ name ] = value; - } catch(e) {} - } - - } else { - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var num, val, hooks, - origName = jQuery.camelCase( name ); - - // Make sure that we're working with the right name - name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - //convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Return, converting to number if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; - } - return val; - }, - - // A method for quickly swapping in/out CSS properties to get correct calculations - swap: function( elem, options, callback, args ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.apply( elem, args || [] ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; - } +\t// Add in style property hooks for overriding the default +\t// behavior of getting and setting a style property +\tcssHooks: { +\t\topacity: { +\t\t\tget: function( elem, computed ) { +\t\t\t\tif ( computed ) { +\t\t\t\t\t// We should always get a number back from opacity +\t\t\t\t\tvar ret = curCSS( elem, "opacity" ); +\t\t\t\t\treturn ret === "" ? "1" : ret; +\t\t\t\t} +\t\t\t} +\t\t} +\t}, + +\t// Exclude the following css properties to add px +\tcssNumber: { +\t\t"columnCount": true, +\t\t"fillOpacity": true, +\t\t"fontWeight": true, +\t\t"lineHeight": true, +\t\t"opacity": true, +\t\t"orphans": true, +\t\t"widows": true, +\t\t"zIndex": true, +\t\t"zoom": true +\t}, + +\t// Add in properties whose names you wish to fix before +\t// setting or getting the value +\tcssProps: { +\t\t// normalize float css property +\t\t"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" +\t}, + +\t// Get and set the style property on a DOM Node +\tstyle: function( elem, name, value, extra ) { +\t\t// Don't set styles on text and comment nodes +\t\tif ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { +\t\t\treturn; +\t\t} + +\t\t// Make sure that we're working with the right name +\t\tvar ret, type, hooks, +\t\t\torigName = jQuery.camelCase( name ), +\t\t\tstyle = elem.style; + +\t\tname = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + +\t\t// gets hook for the prefixed version +\t\t// followed by the unprefixed version +\t\thooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + +\t\t// Check if we're setting a value +\t\tif ( value !== undefined ) { +\t\t\ttype = typeof value; + +\t\t\t// convert relative number strings (+= or -=) to relative numbers. #7345 +\t\t\tif ( type === "string" && (ret = rrelNum.exec( value )) ) { +\t\t\t\tvalue = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); +\t\t\t\t// Fixes bug #9237 +\t\t\t\ttype = "number"; +\t\t\t} + +\t\t\t// Make sure that NaN and null values aren't set. See: #7116 +\t\t\tif ( value == null || type === "number" && isNaN( value ) ) { +\t\t\t\treturn; +\t\t\t} + +\t\t\t// If a number was passed in, add 'px' to the (except for certain CSS properties) +\t\t\tif ( type === "number" && !jQuery.cssNumber[ origName ] ) { +\t\t\t\tvalue += "px"; +\t\t\t} + +\t\t\t// Fixes #8908, it can be done more correctly by specifing setters in cssHooks, +\t\t\t// but it would mean to define eight (for every problematic property) identical functions +\t\t\tif ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { +\t\t\t\tstyle[ name ] = "inherit"; +\t\t\t} + +\t\t\t// If a hook was provided, use that value, otherwise just set the specified value +\t\t\tif ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + +\t\t\t\t// Wrapped to prevent IE from throwing errors when 'invalid' values are provided +\t\t\t\t// Fixes bug #5509 +\t\t\t\ttry { +\t\t\t\t\tstyle[ name ] = value; +\t\t\t\t} catch(e) {} +\t\t\t} + +\t\t} else { +\t\t\t// If a hook was provided get the non-computed value from there +\t\t\tif ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { +\t\t\t\treturn ret; +\t\t\t} + +\t\t\t// Otherwise just get the value from the style object +\t\t\treturn style[ name ]; +\t\t} +\t}, + +\tcss: function( elem, name, extra, styles ) { +\t\tvar num, val, hooks, +\t\t\torigName = jQuery.camelCase( name ); + +\t\t// Make sure that we're working with the right name +\t\tname = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + +\t\t// gets hook for the prefixed version +\t\t// followed by the unprefixed version +\t\thooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + +\t\t// If a hook was provided get the computed value from there +\t\tif ( hooks && "get" in hooks ) { +\t\t\tval = hooks.get( elem, true, extra ); +\t\t} + +\t\t// Otherwise, if a way to get the computed value exists, use that +\t\tif ( val === undefined ) { +\t\t\tval = curCSS( elem, name, styles ); +\t\t} + +\t\t//convert "normal" to computed value +\t\tif ( val === "normal" && name in cssNormalTransform ) { +\t\t\tval = cssNormalTransform[ name ]; +\t\t} + +\t\t// Return, converting to number if forced or a qualifier was provided and val looks numeric +\t\tif ( extra === "" || extra ) { +\t\t\tnum = parseFloat( val ); +\t\t\treturn extra === true || jQuery.isNumeric( num ) ? num || 0 : val; +\t\t} +\t\treturn val; +\t}, + +\t// A method for quickly swapping in/out CSS properties to get correct calculations +\tswap: function( elem, options, callback, args ) { +\t\tvar ret, name, +\t\t\told = {}; + +\t\t// Remember the old values, and insert the new ones +\t\tfor ( name in options ) { +\t\t\told[ name ] = elem.style[ name ]; +\t\t\telem.style[ name ] = options[ name ]; +\t\t} + +\t\tret = callback.apply( elem, args || [] ); + +\t\t// Revert the old values +\t\tfor ( name in options ) { +\t\t\telem.style[ name ] = old[ name ]; +\t\t} + +\t\treturn ret; +\t} }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { - getStyles = function( elem ) { - return window.getComputedStyle( elem, null ); - }; - - curCSS = function( elem, name, _computed ) { - var width, minWidth, maxWidth, - computed = _computed || getStyles( elem ), - - // getPropertyValue is only needed for .css('filter') in IE9, see #12537 - ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, - style = elem.style; - - if ( computed ) { - - if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right - // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels - // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values - if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret; - }; +\tgetStyles = function( elem ) { +\t\treturn window.getComputedStyle( elem, null ); +\t}; + +\tcurCSS = function( elem, name, _computed ) { +\t\tvar width, minWidth, maxWidth, +\t\t\tcomputed = _computed || getStyles( elem ), + +\t\t\t// getPropertyValue is only needed for .css('filter') in IE9, see #12537 +\t\t\tret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, +\t\t\tstyle = elem.style; + +\t\tif ( computed ) { + +\t\t\tif ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { +\t\t\t\tret = jQuery.style( elem, name ); +\t\t\t} + +\t\t\t// A tribute to the "awesome hack by Dean Edwards" +\t\t\t// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right +\t\t\t// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels +\t\t\t// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values +\t\t\tif ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + +\t\t\t\t// Remember the original values +\t\t\t\twidth = style.width; +\t\t\t\tminWidth = style.minWidth; +\t\t\t\tmaxWidth = style.maxWidth; + +\t\t\t\t// Put in the new values to get a computed value out +\t\t\t\tstyle.minWidth = style.maxWidth = style.width = ret; +\t\t\t\tret = computed.width; + +\t\t\t\t// Revert the changed values +\t\t\t\tstyle.width = width; +\t\t\t\tstyle.minWidth = minWidth; +\t\t\t\tstyle.maxWidth = maxWidth; +\t\t\t} +\t\t} + +\t\treturn ret; +\t}; } else if ( document.documentElement.currentStyle ) { - getStyles = function( elem ) { - return elem.currentStyle; - }; - - curCSS = function( elem, name, _computed ) { - var left, rs, rsLeft, - computed = _computed || getStyles( elem ), - ret = computed ? computed[ name ] : undefined, - style = elem.style; - - // Avoid setting ret to empty string here - // so we don't default to auto - if ( ret == null && style && style[ name ] ) { - ret = style[ name ]; - } - - // From the awesome hack by Dean Edwards - // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 - - // If we're not dealing with a regular pixel number - // but a number that has a weird ending, we need to convert it to pixels - // but not position css attributes, as those are proportional to the parent element instead - // and we can't measure the parent instead because it might trigger a "stacking dolls" problem - if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { - - // Remember the original values - left = style.left; - rs = elem.runtimeStyle; - rsLeft = rs && rs.left; - - // Put in the new values to get a computed value out - if ( rsLeft ) { - rs.left = elem.currentStyle.left; - } - style.left = name === "fontSize" ? "1em" : ret; - ret = style.pixelLeft + "px"; - - // Revert the changed values - style.left = left; - if ( rsLeft ) { - rs.left = rsLeft; - } - } - - return ret === "" ? "auto" : ret; - }; +\tgetStyles = function( elem ) { +\t\treturn elem.currentStyle; +\t}; + +\tcurCSS = function( elem, name, _computed ) { +\t\tvar left, rs, rsLeft, +\t\t\tcomputed = _computed || getStyles( elem ), +\t\t\tret = computed ? computed[ name ] : undefined, +\t\t\tstyle = elem.style; + +\t\t// Avoid setting ret to empty string here +\t\t// so we don't default to auto +\t\tif ( ret == null && style && style[ name ] ) { +\t\t\tret = style[ name ]; +\t\t} + +\t\t// From the awesome hack by Dean Edwards +\t\t// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + +\t\t// If we're not dealing with a regular pixel number +\t\t// but a number that has a weird ending, we need to convert it to pixels +\t\t// but not position css attributes, as those are proportional to the parent element instead +\t\t// and we can't measure the parent instead because it might trigger a "stacking dolls" problem +\t\tif ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + +\t\t\t// Remember the original values +\t\t\tleft = style.left; +\t\t\trs = elem.runtimeStyle; +\t\t\trsLeft = rs && rs.left; + +\t\t\t// Put in the new values to get a computed value out +\t\t\tif ( rsLeft ) { +\t\t\t\trs.left = elem.currentStyle.left; +\t\t\t} +\t\t\tstyle.left = name === "fontSize" ? "1em" : ret; +\t\t\tret = style.pixelLeft + "px"; + +\t\t\t// Revert the changed values +\t\t\tstyle.left = left; +\t\t\tif ( rsLeft ) { +\t\t\t\trs.left = rsLeft; +\t\t\t} +\t\t} + +\t\treturn ret === "" ? "auto" : ret; +\t}; } function setPositiveNumber( elem, value, subtract ) { - var matches = rnumsplit.exec( value ); - return matches ? - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : - value; +\tvar matches = rnumsplit.exec( value ); +\treturn matches ? +\t\t// Guard against undefined "subtract", e.g., when used as in cssHooks +\t\tMath.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : +\t\tvalue; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { - var i = extra === ( isBorderBox ? "border" : "content" ) ? - // If we already have the right measurement, avoid augmentation - 4 : - // Otherwise initialize for horizontal or vertical properties - name === "width" ? 1 : 0, - - val = 0; - - for ( ; i < 4; i += 2 ) { - // both box models exclude margin, so add it if we want it - if ( extra === "margin" ) { - val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); - } - - if ( isBorderBox ) { - // border-box includes padding, so remove it if we want content - if ( extra === "content" ) { - val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // at this point, extra isn't border nor margin, so remove border - if ( extra !== "margin" ) { - val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } else { - // at this point, extra isn't content, so add padding - val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // at this point, extra isn't content nor padding, so add border - if ( extra !== "padding" ) { - val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - return val; +\tvar i = extra === ( isBorderBox ? "border" : "content" ) ? +\t\t// If we already have the right measurement, avoid augmentation +\t\t4 : +\t\t// Otherwise initialize for horizontal or vertical properties +\t\tname === "width" ? 1 : 0, + +\t\tval = 0; + +\tfor ( ; i < 4; i += 2 ) { +\t\t// both box models exclude margin, so add it if we want it +\t\tif ( extra === "margin" ) { +\t\t\tval += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); +\t\t} + +\t\tif ( isBorderBox ) { +\t\t\t// border-box includes padding, so remove it if we want content +\t\t\tif ( extra === "content" ) { +\t\t\t\tval -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); +\t\t\t} + +\t\t\t// at this point, extra isn't border nor margin, so remove border +\t\t\tif ( extra !== "margin" ) { +\t\t\t\tval -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); +\t\t\t} +\t\t} else { +\t\t\t// at this point, extra isn't content, so add padding +\t\t\tval += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + +\t\t\t// at this point, extra isn't content nor padding, so add border +\t\t\tif ( extra !== "padding" ) { +\t\t\t\tval += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); +\t\t\t} +\t\t} +\t} + +\treturn val; } function getWidthOrHeight( elem, name, extra ) { - // Start with offset property, which is equivalent to the border-box value - var valueIsBorderBox = true, - val = name === "width" ? elem.offsetWidth : elem.offsetHeight, - styles = getStyles( elem ), - isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // some non-html elements return undefined for offsetWidth, so check for null/undefined - // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 - // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 - if ( val <= 0 || val == null ) { - // Fall back to computed then uncomputed css if necessary - val = curCSS( elem, name, styles ); - if ( val < 0 || val == null ) { - val = elem.style[ name ]; - } - - // Computed unit is not pixels. Stop here and return. - if ( rnumnonpx.test(val) ) { - return val; - } - - // we need the check for style in case a browser which returns unreliable values - // for getComputedStyle silently falls back to the reliable elem.style - valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); - - // Normalize "", auto, and prepare for extra - val = parseFloat( val ) || 0; - } - - // use the active box-sizing model to add/subtract irrelevant styles - return ( val + - augmentWidthOrHeight( - elem, - name, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles - ) - ) + "px"; +\t// Start with offset property, which is equivalent to the border-box value +\tvar valueIsBorderBox = true, +\t\tval = name === "width" ? elem.offsetWidth : elem.offsetHeight, +\t\tstyles = getStyles( elem ), +\t\tisBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + +\t// some non-html elements return undefined for offsetWidth, so check for null/undefined +\t// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 +\t// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 +\tif ( val <= 0 || val == null ) { +\t\t// Fall back to computed then uncomputed css if necessary +\t\tval = curCSS( elem, name, styles ); +\t\tif ( val < 0 || val == null ) { +\t\t\tval = elem.style[ name ]; +\t\t} + +\t\t// Computed unit is not pixels. Stop here and return. +\t\tif ( rnumnonpx.test(val) ) { +\t\t\treturn val; +\t\t} + +\t\t// we need the check for style in case a browser which returns unreliable values +\t\t// for getComputedStyle silently falls back to the reliable elem.style +\t\tvalueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + +\t\t// Normalize "", auto, and prepare for extra +\t\tval = parseFloat( val ) || 0; +\t} + +\t// use the active box-sizing model to add/subtract irrelevant styles +\treturn ( val + +\t\taugmentWidthOrHeight( +\t\t\telem, +\t\t\tname, +\t\t\textra || ( isBorderBox ? "border" : "content" ), +\t\t\tvalueIsBorderBox, +\t\t\tstyles +\t\t) +\t) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { - var doc = document, - display = elemdisplay[ nodeName ]; - - if ( !display ) { - display = actualDisplay( nodeName, doc ); - - // If the simple way fails, read from inside an iframe - if ( display === "none" || !display ) { - // Use the already-created iframe if possible - iframe = ( iframe || - jQuery("