示例#1
0
class koVisualBasicLanguage(KoCommonBasicLanguageService):
    name = "VisualBasic"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{7B83199C-6C30-43ef-9087-329831FC6425}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".vb"
    commentDelimiterInfo = {
        "line": [ "'",  "rem ", "REM "  ],
    }

    # Problems: 'private' and 'public' and 'shared' can come before a function name.
    def __init__(self):
        KoCommonBasicLanguageService.__init__(self)
        del self.matchingSoftChars["'"]
     
    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_VB)
            self._lexer.setKeywords(0, keywords)
            self._lexer.supportsFolding = 0
        return self._lexer
示例#2
0
class koVisualBasicLanguage(KoCommonBasicLanguageService):
    name = "VisualBasic"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{7B83199C-6C30-43ef-9087-329831FC6425}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".vb"
    commentDelimiterInfo = {
        "line": ["'", "rem ", "REM "],
    }

    # Problems: 'private' and 'public' and 'shared' can come before a function name.
    def __init__(self):
        KoCommonBasicLanguageService.__init__(self)
        del self.matchingSoftChars["'"]

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_VB)
            self._lexer.setKeywords(0, keywords)
            self._lexer.supportsFolding = 0
        return self._lexer
示例#3
0
    def get_lexer(self):
        if self._lexer is None:
            # Initialize styling information.
            cmake_style_map = {
                'default': ('SCE_CMAKE_DEFAULT',),
                'comments': ('SCE_CMAKE_COMMENT',),
                'keywords': ('SCE_CMAKE_COMMANDS',),
                'keywords2': ('SCE_CMAKE_PARAMETERS',),
                'variables': ('SCE_CMAKE_VARIABLE', 'SCE_CMAKE_STRINGVAR'),
                'strings': ('SCE_CMAKE_STRINGDQ', 'SCE_CMAKE_STRINGLQ', 'SCE_CMAKE_STRINGRQ'),
                'numbers': ('SCE_CMAKE_NUMBER',),
                'macro': ('SCE_CMAKE_MACRODEF',),
                'section': ('SCE_CMAKE_WHILEDEF', 'SCE_CMAKE_FOREACHDEF', 'SCE_CMAKE_IFDEFINEDEF'),
                'user': ('SCE_CMAKE_USERDEFINED',),
            }
            # Set style mapping.
            import styles
            styles.addSharedStyles(cmake_style_map)
            styles.StateMap[self.name] = cmake_style_map

            # Initalize the lexer.
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CMAKE)
            self._lexer.setKeywords(0, self.cmake_commands)
            self._lexer.setKeywords(1, self.cmake_variables)
        return self._lexer
示例#4
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(self.sciLexer)
         self._lexer.setKeywords(0, self._keywords)
         self._lexer.supportsFolding = 1
     return self._lexer
示例#5
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(sci_constants.SCLEX_BASH)
         self._lexer.setKeywords(0, self.bash_keywords1 + self.bash_keywords2)
         self._lexer.supportsFolding = 1
     return self._lexer
示例#6
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_VB)
         self._lexer.setKeywords(0, keywords)
         self._lexer.supportsFolding = 0
     return self._lexer
示例#7
0
 def get_lexer(self):
     if self._lexer is None:
         # Initalize the lexer.
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CMAKE)
         self._lexer.setKeywords(0, self.cmake_commands)
         self._lexer.setKeywords(1, self.cmake_variables)
     return self._lexer
示例#8
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(sci_constants.SCLEX_CPP)
         self._lexer.setKeywords(0, HLSLLangInfo.keywords)
         self._lexer.setProperty('fold.cpp.syntax.based', '1')
         self._lexer.supportsFolding = 1
     return self._lexer
示例#9
0
class koMatlabLanguage(KoLanguageKeywordBase):
    name = "Matlab"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{913BAE69-8E17-4c91-B855-687F0A34CFF6}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".m.matlab"
    extraFileAssociations = ['*.m', '*.matlab']
    commentDelimiterInfo = { "line": [ "%", "#" ]  }
    supportsSmartIndent = "keyword"
    # See comment in koLuaLanguage.py for why some keywords are in both
    # _indenting_statements and _keyword_dedenting_keywords
    _indenting_statements = ['function', 'if', 'for', 'parfor',
                             'while', 'else', 'do',
                             'elseif',
                             'switch', 'case', 'otherwise']
    _dedenting_statements = ['break', 'continue', 'return', 'error']
    _keyword_dedenting_keywords = ['end', 'else', 'elseif',
                                   'case', 'otherwise', 'until']

    _keywords = """break case catch classdef continue else elseif end error for
                function global if otherwise parfor persistent return
                spmd switch try while""".split()
    sciLexer = components.interfaces.ISciMoz.SCLEX_MATLAB

    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _block_comment_styles = [sci_constants.SCE_MATLAB_COMMENT,],
            _indent_styles = [sci_constants.SCE_MATLAB_OPERATOR],
            _variable_styles = [sci_constants.SCE_MATLAB_IDENTIFIER],
            _lineup_close_styles = [sci_constants.SCE_MATLAB_OPERATOR],
            _lineup_styles = [sci_constants.SCE_MATLAB_OPERATOR],
            _keyword_styles = [sci_constants.SCE_MATLAB_KEYWORD],
            _default_styles = [sci_constants.SCE_MATLAB_DEFAULT],
            _ignorable_styles = [sci_constants.SCE_MATLAB_COMMENT,
                                 sci_constants.SCE_MATLAB_NUMBER],
            )

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(self.sciLexer)
            self._lexer.setKeywords(0, self._keywords)
            self._lexer.supportsFolding = 1
        return self._lexer

    # matches:
    # function [output] = name(input)
    # classdef name < super
    # %% cell title
    namedBlockDescription = 'Matlab functions and classes'
    namedBlockRE = r'(?:\b(?:function|classdef)\s+\w+|^\s*%%\s+\w+.*)'
    searchURL = "http://www.mathworks.com/help/search/doc/en/?qdoc=%W"

    sample = r"""function b = acyclic(adj_mat, directed)
示例#10
0
class koErlangLanguage(KoLanguageBase):
    name = "Erlang"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" % (name)
    _reg_clsid_ = "{0153c47a-f668-41d4-8519-9ecd6b1c5ba0}"
    _reg_categories_ = [("komodo-language", name)]

    _stateMap = {
        "default": ("SCE_ERLANG_DEFAULT",),
        "comments": (
            "SCE_ERLANG_COMMENT",
            "SCE_ERLANG_COMMENT_FUNCTION",
            "SCE_ERLANG_COMMENT_MODULE",
            "SCE_ERLANG_COMMENT_DOC",
            "SCE_ERLANG_COMMENT_DOC_MACRO",
        ),
        "variables": ("SCE_ERLANG_VARIABLE",),
        "numbers": ("SCE_ERLANG_NUMBER",),
        "keywords": ("SCE_ERLANG_KEYWORD",),
        "strings": ("SCE_ERLANG_STRING", "SCE_ERLANG_CHARACTER"),
        "operators": ("SCE_ERLANG_OPERATOR",),
        "functions": ("SCE_ERLANG_FUNCTION_NAME",),
        "macros": ("SCE_ERLANG_MACRO",),
        "records": ("SCE_ERLANG_RECORD",),
        "atoms": ("SCE_ERLANG_ATOM",),
        "nodes": ("SCE_ERLANG_NODE_NAME",),
        "unknown": ("SCE_ERLANG_UNKNOWN",),
    }
    defaultExtension = ".erl"
    commentDelimiterInfo = {"line": ["%"]}

    sample = """-module(test).
-export([fac/1]).

fac(0) -> 1;
fac(N) -> N * fac(N-1).
"""

    def __init__(self):
        KoLanguageBase.__init__(self)
        self._fastCharData = ErlangFastCharData(
            trigger_char=".",
            style_list=(sci_constants.SCE_ERLANG_OPERATOR,),
            skippable_chars_by_style={sci_constants.SCE_ERLANG_OPERATOR: "])"},
        )

    _keywords = """
        after begin case catch cond end fun if let of query receive when
        define record export import include include_lib ifdef ifndef else endif undef
        apply attribute call do in letrec module primop try""".split()

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_ERLANG)
            self._lexer.setKeywords(0, self._keywords)
        return self._lexer
示例#11
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(
             components.interfaces.ISciMoz.SCLEX_POWERBASIC)
         self._lexer.setKeywords(0, self._keywords_preprocessor + \
                                    self._keywords_functions + \
                                    self._keywords_proceedures + \
                                    self._keywords_datatypes + \
                                    self._keywords_options)
         self._lexer.supportsFolding = 1
     return self._lexer
示例#12
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(self.sciLexer)
         self._lexer.setKeywords(0, self._keywords)
         self._lexer.supportsFolding = 1
     return self._lexer
示例#13
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_VB)
         self._lexer.setKeywords(0, keywords)
         self._lexer.supportsFolding = 0
     return self._lexer
示例#14
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(sci_constants.SCLEX_CPP)
         self._lexer.setKeywords(0, HLSLLangInfo.keywords)
         self._lexer.setProperty('fold.cpp.syntax.based', '1')
         self._lexer.supportsFolding = 1
     return self._lexer
示例#15
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CPP)
         self._lexer.supportsFolding = 1
         self._lexer.setProperty('lexer.cpp.allow.dollars', '0')
         self._lexer.setProperty('fold.cpp.syntax.based', '1')
         self._lexer.setProperty('lexer.cpp.backquoted.strings', '1')
         self._lexer.setKeywords(0, GoLangInfo.reserved_keywords)
         # The CPP lexer reserves keywords(2) for comment doc keywords and
         # keywords(3) for "SCE_C_GLOBALCLASS", so treat the
         # predeclared_identifiers (like 'bool') and
         # the predefined_functions (like 'append') as the same.
         other_words = (GoLangInfo.predeclared_identifiers.
                        union(GoLangInfo.predeclared_functions))
         self._lexer.setKeywords(1, other_words)
     return self._lexer
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(
             components.interfaces.ISciMoz.SCLEX_POWERBASIC)
         self._lexer.setKeywords(0, self._keywords_preprocessor + \
                                    self._keywords_functions + \
                                    self._keywords_proceedures + \
                                    self._keywords_datatypes + \
                                    self._keywords_options)
         self._lexer.supportsFolding = 1
     return self._lexer
示例#17
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CPP)
         self._lexer.supportsFolding = 1
         self._lexer.setProperty("lexer.cpp.allow.dollars", "0")
         self._lexer.setProperty("fold.cpp.syntax.based", "1")
         self._lexer.setProperty("lexer.cpp.backquoted.strings", "1")
         self._lexer.setKeywords(0, GoLangInfo.reserved_keywords)
         # The CPP lexer reserves keywords(2) for comment doc keywords and
         # keywords(3) for "SCE_C_GLOBALCLASS", so treat the
         # predeclared_identifiers (like 'bool') and
         # the predefined_functions (like 'append') as the same.
         other_words = GoLangInfo.predeclared_identifiers.union(GoLangInfo.predeclared_functions)
         self._lexer.setKeywords(1, other_words)
     return self._lexer
示例#18
0
class koGoLanguage(KoLanguageBase, KoLanguageBaseDedentMixin):
    name = "Go"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" % (name)
    _reg_clsid_ = "{2d6ed8b6-f079-441a-8b5a-10ef781cb989}"
    _reg_categories_ = [("komodo-language", name)]

    modeNames = ["go"]
    primary = 1
    internal = 0
    accessKey = "g"
    defaultExtension = ".go"
    commentDelimiterInfo = {"line": ["//"], "block": [("/*", "*/")], "markup": "*"}
    _dedenting_statements = [u"goto", u"return", u"break", u"continue"]

    namedBlockRE = "^[ \t]*?(func\s+(?:\(.*?\)\s*)?\w|package\s+\w)"
    namedBlockDescription = "Go functions, methods and packages"
    supportsSmartIndent = "brace"
    # The following sample contains embedded tabs because that's the Go way.
    sample = r"""\
package commands

import (
	"encoding/json"
)
type Filters []string
func (f *Filters) String() string {
	a := "a string"
	b := 'c' // a char
	c := 43 // a num
	return fmt.Sprint(*f)
}
/* Block comment
on these two lines */
    """

    def __init__(self):
        KoLanguageBase.__init__(self)
        self._style_info.update(
            _block_comment_styles=[
                sci_constants.SCE_C_COMMENT,
                sci_constants.SCE_C_COMMENTDOC,
                sci_constants.SCE_C_COMMENTDOCKEYWORD,
                sci_constants.SCE_C_COMMENTDOCKEYWORDERROR,
            ],
            _variable_styles=[components.interfaces.ISciMoz.SCE_C_IDENTIFIER],
        )
        self._setupIndentCheckSoftChar()
        self._fastCharData = FastCharData(
            trigger_char=";",
            style_list=(sci_constants.SCE_C_OPERATOR,),
            skippable_chars_by_style={sci_constants.SCE_C_OPERATOR: "])"},
            for_check=True,
        )
        # And add the new default prefs if they don't exist
        globalPrefs = (
            components.classes["@activestate.com/koPrefService;1"]
            .getService(components.interfaces.koIPrefService)
            .prefs
        )
        # Chunk adding prefs based on which ones they were added with.
        if not globalPrefs.hasPref("gocodeDefaultLocation"):
            globalPrefs.setStringPref("gocodeDefaultLocation", "")
        if not globalPrefs.hasPref("godefDefaultLocation"):
            globalPrefs.setStringPref("godefDefaultLocation", "")
        if not globalPrefs.hasPref("golangDefaultLocation"):
            globalPrefs.setStringPref("golangDefaultLocation", "")
            globalPrefs.setStringPref("Go/newEncoding", "utf-8")
            globalPrefs.setLongPref("Go/indentWidth", 8)
            globalPrefs.setBooleanPref("Go/useTabs", True)
            # TODO: Add formatter prefs along the lines of:
            # <!-- Go formatter -->
            # <preference-set >
            # <string id="formatter_name">generic</string>
            # <string id="lang">Go</string>
            # <string id="name">Go Reformatter</string>
            # <string id="uuid">{286d5b45-a54e-4317-b3c8-da4dc35673a4}</string>
            # </preference-set>

    def getLanguageService(self, iid):
        return KoLanguageBase.getLanguageService(self, iid)

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CPP)
            self._lexer.supportsFolding = 1
            self._lexer.setProperty("lexer.cpp.allow.dollars", "0")
            self._lexer.setProperty("fold.cpp.syntax.based", "1")
            self._lexer.setProperty("lexer.cpp.backquoted.strings", "1")
            self._lexer.setKeywords(0, GoLangInfo.reserved_keywords)
            # The CPP lexer reserves keywords(2) for comment doc keywords and
            # keywords(3) for "SCE_C_GLOBALCLASS", so treat the
            # predeclared_identifiers (like 'bool') and
            # the predefined_functions (like 'append') as the same.
            other_words = GoLangInfo.predeclared_identifiers.union(GoLangInfo.predeclared_functions)
            self._lexer.setKeywords(1, other_words)
        return self._lexer
示例#19
0
class koPascalLanguage(KoLanguageKeywordBase):
    name = "Pascal"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{8AE35E4C-0EC9-49f2-A534-8FEAB91D261D}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".pas"
    commentDelimiterInfo = {
        # See the following for info on Pascal comments:
        #  http://www.math.uni-hamburg.de/it/software/fpk/ref/node7.html
        #XXX The line Pascal comment is a Delphi only thing, so I am leaving
        #    it out for now.
        #"line": [ "//" ],
        "block": [ ("{",  "}"),
                   ("(*", "*)") ],
        "markup": "*",
    }
    supportsSmartIndent = "keyword"
    _indenting_statements = ['begin', 'record', 'repeat', 'case', ]
    _dedenting_statements = ['goto', 'halt', ]
    _keyword_dedenting_keywords = ['end', 'until', ]

    _stateMap = {
        'default': ('SCE_PAS_DEFAULT',),
        'keywords': ('SCE_PAS_WORD', 'SCE_PAS_ASM'),
        'comments': ('SCE_PAS_COMMENT', 'SCE_PAS_COMMENT2', 'SCE_PAS_COMMENTLINE',),
        'identifiers': ('SCE_PAS_IDENTIFIER',),
        'preprocessor': ('SCE_PAS_PREPROCESSOR', 'SCE_PAS_PREPROCESSOR2'),
        'numbers': ('SCE_PAS_NUMBER', 'SCE_PAS_HEXNUMBER',),
        'strings': ('SCE_PAS_STRING', 'SCE_PAS_STRINGEOL', 'SCE_PAS_CHARACTER',),
        }

    sample = """
program MyProg(input, output)
(* Warning: this program might not compile. *)
  begin
    { that's because there's no
      Pascal compiler on this machine.
    }
    var myVar:integer;
    myVar := 5;
    if (myVar > 3) begin
      writeln("Pascal is fun!!!!")
    end
  end
end.
"""    
    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _block_comment_styles = [sci_constants.SCE_PAS_COMMENT,
                                     sci_constants.SCE_PAS_COMMENT2,
                                     sci_constants.SCE_PAS_COMMENTLINE],
            _indent_styles = [sci_constants.SCE_PAS_OPERATOR],
            _variable_styles = [sci_constants.SCE_PAS_IDENTIFIER],
            _lineup_close_styles = [sci_constants.SCE_PAS_OPERATOR],
            _lineup_styles = [sci_constants.SCE_PAS_OPERATOR],
            _keyword_styles = [sci_constants.SCE_PAS_WORD],
            _default_styles = [sci_constants.SCE_PAS_DEFAULT],
            _ignorable_styles = [sci_constants.SCE_PAS_COMMENT,
                                 sci_constants.SCE_PAS_COMMENT2,
                                 sci_constants.SCE_PAS_COMMENTLINE,
                                 sci_constants.SCE_PAS_NUMBER],
            )
        self._fastCharData = \
            FastCharData(trigger_char=";",
                         style_list=(sci_constants.SCE_PAS_OPERATOR, ),
                         skippable_chars_by_style={ sci_constants.SCE_PAS_OPERATOR : "])" },
                         for_check=True)

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_PASCAL)
            self._lexer.setKeywords(0, self._keywords)
            self._lexer.setKeywords(1, self._keywords2)
            self._lexer.supportsFolding = 1
        return self._lexer

    _keywords = """and array asm begin case cdecl class const constructor default 
destructor div do downto else end end. except exit exports external far file 
finalization finally for function goto if implementation in index inherited 
initialization inline interface label library message mod near nil not 
object of on or out overload override packed pascal private procedure program 
property protected public published raise read record register repeat resourcestring 
safecall set shl shr stdcall stored string then threadvar to try type unit 
until uses var virtual while with write writeln xor""".split()

    _keywords2 = """write read default public protected private property
            published stored""".split()
示例#20
0
class koPascalLanguage(KoLanguageKeywordBase):
    name = "Pascal"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" % (name)
    _reg_clsid_ = "{8AE35E4C-0EC9-49f2-A534-8FEAB91D261D}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".pas"
    commentDelimiterInfo = {
        # See the following for info on Pascal comments:
        #  http://www.math.uni-hamburg.de/it/software/fpk/ref/node7.html
        # XXX The line Pascal comment is a Delphi only thing, so I am leaving
        #    it out for now.
        # "line": [ "//" ],
        "block": [("{", "}"), ("(*", "*)")],
        "markup": "*",
    }
    supportsSmartIndent = "keyword"
    _indenting_statements = ["begin", "record", "repeat", "case"]
    _dedenting_statements = ["goto", "halt"]
    _keyword_dedenting_keywords = ["end", "until"]

    _stateMap = {
        "default": ("SCE_PAS_DEFAULT",),
        "keywords": ("SCE_PAS_WORD", "SCE_PAS_ASM"),
        "comments": ("SCE_PAS_COMMENT", "SCE_PAS_COMMENT2", "SCE_PAS_COMMENTLINE"),
        "identifiers": ("SCE_PAS_IDENTIFIER",),
        "preprocessor": ("SCE_PAS_PREPROCESSOR", "SCE_PAS_PREPROCESSOR2"),
        "numbers": ("SCE_PAS_NUMBER", "SCE_PAS_HEXNUMBER"),
        "strings": ("SCE_PAS_STRING", "SCE_PAS_STRINGEOL", "SCE_PAS_CHARACTER"),
    }

    sample = """
program MyProg(input, output)
(* Warning: this program might not compile. *)
  begin
    { that's because there's no
      Pascal compiler on this machine.
    }
    var myVar:integer;
    myVar := 5;
    if (myVar > 3) begin
      writeln("Pascal is fun!!!!")
    end
  end
end.
"""

    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _block_comment_styles=[
                sci_constants.SCE_PAS_COMMENT,
                sci_constants.SCE_PAS_COMMENT2,
                sci_constants.SCE_PAS_COMMENTLINE,
            ],
            _indent_styles=[sci_constants.SCE_PAS_OPERATOR],
            _variable_styles=[sci_constants.SCE_PAS_IDENTIFIER],
            _lineup_close_styles=[sci_constants.SCE_PAS_OPERATOR],
            _lineup_styles=[sci_constants.SCE_PAS_OPERATOR],
            _keyword_styles=[sci_constants.SCE_PAS_WORD],
            _default_styles=[sci_constants.SCE_PAS_DEFAULT],
            _ignorable_styles=[
                sci_constants.SCE_PAS_COMMENT,
                sci_constants.SCE_PAS_COMMENT2,
                sci_constants.SCE_PAS_COMMENTLINE,
                sci_constants.SCE_PAS_NUMBER,
            ],
        )
        self._fastCharData = FastCharData(
            trigger_char=";",
            style_list=(sci_constants.SCE_PAS_OPERATOR,),
            skippable_chars_by_style={sci_constants.SCE_PAS_OPERATOR: "])"},
            for_check=True,
        )

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_PASCAL)
            self._lexer.setKeywords(0, self._keywords)
            self._lexer.setKeywords(1, self._keywords2)
            self._lexer.supportsFolding = 1
        return self._lexer

    _keywords = """and array asm begin case cdecl class const constructor default 
destructor div do downto else end end. except exit exports external far file 
finalization finally for function goto if implementation in index inherited 
initialization inline interface label library message mod near nil not 
object of on or out overload override packed pascal private procedure program 
property protected public published raise read record register repeat resourcestring 
safecall set shl shr stdcall stored string then threadvar to try type unit 
until uses var virtual while with write writeln xor""".split()

    _keywords2 = """write read default public protected private property
            published stored""".split()
示例#21
0
class koLuaLanguage(KoLanguageKeywordBase):
    name = "Lua"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{D3C94E8B-B75C-4fa4-BC4D-986F68ACD33C}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".lua"
    commentDelimiterInfo = {
        "line": [ "--" ],
        "block": [ ("--[[", "]]") ],
    }
    supportsSmartIndent = "keyword"
    _indenting_statements = ['function', 'if', 'for', 'repeat', 'while', 'else',
                             'elseif', 'do']
    _dedenting_statements = ['break', 'continue', 'return', 'error']
    # These trigger a dedent when entered, but then count +1
    # This might be better than putting 'else' in both
    # _indenting_statements and _keyword_dedenting_keywords
    _keyword_dedenting_keywords = ['end', 'else', 'elseif', 'until']
    
    sample = """require "lfs"

function dirtree(dir)
  assert(dir and dir ~= "", "directory parameter is missing or empty")
  if string.sub(dir, -1) == "/" then
    dir=string.sub(dir, 1, -2)
  end

  local diriters = {lfs.dir(dir)}
  local dirs = {dir}

  return function()
    repeat 
      local entry = diriters[#diriters]()
      if entry then 
        if entry ~= "." and entry ~= ".." then 
          local filename = table.concat(dirs, "/").."/"..entry
          local attr = lfs.attributes(filename)
          if attr.mode == "directory" then 
            table.insert(dirs, entry)
            table.insert(diriters, lfs.dir(filename))
          end
          return filename, attr
        end
      else
        table.remove(dirs)
        table.remove(diriters)
      end
    until #diriters==0
  end
end
    """

    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _block_comment_styles = [sci_constants.SCE_LUA_COMMENTLINE,
                                     sci_constants.SCE_LUA_COMMENTDOC],
            _indent_styles = [sci_constants.SCE_LUA_OPERATOR],
            _variable_styles = [sci_constants.SCE_LUA_IDENTIFIER],
            _lineup_close_styles = [sci_constants.SCE_LUA_OPERATOR],
            _lineup_styles = [sci_constants.SCE_LUA_OPERATOR],
            _keyword_styles = [sci_constants.SCE_LUA_WORD,
                               sci_constants.SCE_LUA_WORD2,
                               sci_constants.SCE_LUA_WORD3,
                               sci_constants.SCE_LUA_WORD4,
                               sci_constants.SCE_LUA_WORD5,
                               sci_constants.SCE_LUA_WORD6,
                               sci_constants.SCE_LUA_WORD7,
                               sci_constants.SCE_LUA_WORD8,
                               ],
            _default_styles = [sci_constants.SCE_LUA_DEFAULT],
            _ignorable_styles = [sci_constants.SCE_LUA_COMMENT,
                                 sci_constants.SCE_LUA_COMMENTLINE,
                                 sci_constants.SCE_LUA_COMMENTDOC,
                                 sci_constants.SCE_LUA_NUMBER],
            )

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_LUA)
            self._lexer.setKeywords(0, self._keywords)
            self._lexer.setKeywords(1, self._keywords1)
            self._lexer.supportsFolding = 1
        return self._lexer


    _keywords = ["and", "break", "do", "else", "elseif", "end", "false", "for", "function",
                 "if", "in", "local", "nil", "not", "or", "repeat", "return", "then",
                 "true", "until", "while"]
    _keywords1 = ['require', 'assert', 'string', 'table',
                  'collectgarbage', 'dofile', 'error', '_G', 'getmetatable',
                  'ipairs', 'load', 'loadfile', 'next', 'pairs', 'pcall',
                  'print', 'rawequal', 'rawget', 'rawlen', 'rawset', 'select',
                  'setmetatable', 'tonumber', 'tostring', 'type', '_VERSION', 'xpcall',]
    
    #XXX: Override _indentingOrDedentingStatement looking for things like
    #   return function ...
    

    # Override:
    # Handle return ... function differently

    def computeIndent(self, scimoz, indentStyle, continueComments):
        if continueComments:
            return KoLanguageKeywordBase.computeIndent(self, scimoz, indentStyle, continueComments)
        calculatedData = self.getTokenDataForComputeIndent(scimoz, self._style_info)
        indent = self._computeIndent(scimoz, indentStyle, continueComments, self._style_info, calculatedData)
        if indent is not None:
            return indent
        return KoLanguageKeywordBase.computeIndent(self, scimoz, indentStyle, continueComments, calculatedData=calculatedData)

    def _computeIndent(self, scimoz, indentStyle, continueComments, style_info,
                       calculatedData):
        non_ws_tokens = calculatedData['non_ws_tokens']
        if not self._lookingAtReturnFunction(non_ws_tokens, style_info):
            return None
        tok0 = calculatedData['tokens'][0]
        if tok0.style in style_info._default_styles:
            currWSLen = len(tok0.text.expandtabs(scimoz.tabWidth))
            newWSLen = currWSLen + scimoz.indent
        else:
            newWSLen = scimoz.indent
        return scimozindent.makeIndentFromWidth(scimoz, newWSLen)

    def _lookingAtReturnFunction(self, non_ws_tokens, style_info):
        return (len(non_ws_tokens) >= 2
                and non_ws_tokens[0].style in style_info._keyword_styles
                and non_ws_tokens[0].text == "return"
                and non_ws_tokens[1].style in style_info._keyword_styles
                and non_ws_tokens[1].text == "function")
示例#22
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_ERLANG)
         self._lexer.setKeywords(0, self._keywords)
     return self._lexer
示例#23
0
class koMatlabLanguage(KoLanguageKeywordBase):
    name = "Matlab"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" % (name)
    _reg_clsid_ = "{913BAE69-8E17-4c91-B855-687F0A34CFF6}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".m.matlab"
    extraFileAssociations = ["*.m", "*.matlab"]
    commentDelimiterInfo = {"line": ["%", "#"]}
    supportsSmartIndent = "keyword"
    # See comment in koLuaLanguage.py for why some keywords are in both
    # _indenting_statements and _keyword_dedenting_keywords
    _indenting_statements = [
        "function",
        "if",
        "for",
        "parfor",
        "while",
        "else",
        "do",
        "elseif",
        "switch",
        "case",
        "otherwise",
    ]
    _dedenting_statements = ["break", "continue", "return", "error"]
    _keyword_dedenting_keywords = ["end", "else", "elseif", "case", "otherwise", "until"]

    _keywords = """break case catch classdef continue else elseif end error for
                function global if otherwise parfor persistent return
                spmd switch try while""".split()
    sciLexer = components.interfaces.ISciMoz.SCLEX_MATLAB

    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _block_comment_styles=[sci_constants.SCE_MATLAB_COMMENT],
            _indent_styles=[sci_constants.SCE_MATLAB_OPERATOR],
            _variable_styles=[sci_constants.SCE_MATLAB_IDENTIFIER],
            _lineup_close_styles=[sci_constants.SCE_MATLAB_OPERATOR],
            _lineup_styles=[sci_constants.SCE_MATLAB_OPERATOR],
            _keyword_styles=[sci_constants.SCE_MATLAB_KEYWORD],
            _default_styles=[sci_constants.SCE_MATLAB_DEFAULT],
            _ignorable_styles=[sci_constants.SCE_MATLAB_COMMENT, sci_constants.SCE_MATLAB_NUMBER],
        )

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(self.sciLexer)
            self._lexer.setKeywords(0, self._keywords)
            self._lexer.supportsFolding = 1
        return self._lexer

    # matches:
    # function [output] = name(input)
    # classdef name < super
    # %% cell title
    namedBlockDescription = "Matlab functions and classes"
    namedBlockRE = r"(?:\b(?:function|classdef)\s+\w+|^\s*%%\s+\w+.*)"
    searchURL = "http://www.mathworks.com/help/search/doc/en/?qdoc=%W"

    sample = r"""function b = acyclic(adj_mat, directed)
示例#24
0
class koGoLanguage(KoLanguageBase, KoLanguageBaseDedentMixin):
    name = "Go"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{2d6ed8b6-f079-441a-8b5a-10ef781cb989}"
    _reg_categories_ = [("komodo-language", name)]
    # Copy the base interfaces.
    _com_interfaces_ = KoLanguageBase._com_interfaces_[:]
    # Add koIInterpolationCallback - but it's only available in version 9 and
    # above - so catch the exception for earlier versions.
    try:
        _com_interfaces_.append(components.interfaces.koIInterpolationCallback)
    except:
        log.warn("koIInterpolationCallback does not exist")

    modeNames = ['go']
    primary = 1
    internal = 0
    accessKey = 'g'
    defaultExtension = ".go"
    commentDelimiterInfo = {
        "line": [ "//" ],
        "block": [ ("/*", "*/") ],
        "markup": "*",
    }
    _dedenting_statements = [u'goto', u'return', u'break', u'continue']
    
    namedBlockRE = "^[ \t]*?(func\s+(?:\(.*?\)\s*)?\w|package\s+\w)"
    namedBlockDescription = 'Go functions, methods and packages'
    supportsSmartIndent = "brace"
    # The following sample contains embedded tabs because that's the Go way.
    sample = r"""\
package commands

import (
	"encoding/json"
)
type Filters []string
func (f *Filters) String() string {
	a := "a string"
	b := 'c' // a char
	c := 43 // a num
	return fmt.Sprint(*f)
}
/* Block comment
on these two lines */
    """

    def __init__(self):
        KoLanguageBase.__init__(self)
        self._style_info.update(
            _block_comment_styles = [sci_constants.SCE_C_COMMENT,
                                     sci_constants.SCE_C_COMMENTDOC,
                                     sci_constants.SCE_C_COMMENTDOCKEYWORD,
                                     sci_constants.SCE_C_COMMENTDOCKEYWORDERROR],
            _variable_styles = [components.interfaces.ISciMoz.SCE_C_IDENTIFIER]
            )
        self._setupIndentCheckSoftChar()
        self._fastCharData = \
            FastCharData(trigger_char=";",
                         style_list=(sci_constants.SCE_C_OPERATOR,),
                         skippable_chars_by_style={ sci_constants.SCE_C_OPERATOR : "])",},
                         for_check=True)

        # Add extensible items (available in komodo 9 and higher).
        if 'koIInterpolationService' in components.interfaces.keys():
            interpolateSvc = components.classes["@activestate.com/koInterpolationService;1"].\
                                getService(components.interfaces.koIInterpolationService)
            try:
                interpolateSvc.addCode('go', self)
            except Exception:
                log.warn("Unable to add 'go' interpolation shortcut")

    def interpolationCallback(self, code, fileName, lineNum, word, selection,
                              projectFile, prefs):
        if code == 'go':
            golangInfoEx = components.classes["@activestate.com/koAppInfoEx?app=Go;1"].\
                        getService(components.interfaces.koIAppInfoEx)
            return golangInfoEx.executablePath
        raise RuntimeError("Unexpected go code %r" % (code, ))

    def getLanguageService(self, iid):
        return KoLanguageBase.getLanguageService(self, iid)

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CPP)
            self._lexer.supportsFolding = 1
            self._lexer.setProperty('lexer.cpp.allow.dollars', '0')
            self._lexer.setProperty('fold.cpp.syntax.based', '1')
            self._lexer.setProperty('lexer.cpp.backquoted.strings', '1')
            self._lexer.setKeywords(0, GoLangInfo.reserved_keywords)
            # The CPP lexer reserves keywords(2) for comment doc keywords and
            # keywords(3) for "SCE_C_GLOBALCLASS", so treat the
            # predeclared_identifiers (like 'bool') and
            # the predefined_functions (like 'append') as the same.
            other_words = (GoLangInfo.predeclared_identifiers.
                           union(GoLangInfo.predeclared_functions))
            self._lexer.setKeywords(1, other_words)
        return self._lexer
示例#25
0
class koHLSLLanguage(KoLanguageBase):
    name = "HLSL"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{fd0846b3-ff7f-41af-b324-179783084469}"
    _reg_categories_ = [("komodo-language", name)]

    primary = 0
    defaultExtension = ".hlsl"
    commentDelimiterInfo = {
        "line": ["//"],
        "block": [("/*", "*/")],
        "markup": "*",
    }
    _dedenting_statements = [u'throw', u'return', u'break', u'continue']
    _indenting_statements = [u'case']
    searchURL = "http://www.google.com/search?q=hlsl+site%3Amicrosoft.com%2F+%W"
    # matches:
    # function name
    # name: function
    # name = function
    # class.prototype.name = function
    namedBlockDescription = 'HLSL functions and classes'
    namedBlockRE = r'^[ |\t]*?(?:([\w|\.|_]*?)\s*=\s*function|function\s*([\w|\_]*?)|([\w|\_]*?)\s*:\s*function).*?$'
    supportsSmartIndent = "brace"
    sample = """
     float4 normal = mul(IN.Normal, ModelViewIT);
     normal.w = 0.0;
     normal = normalize(normal);
     float4 light = normalize(LightVec);
     float4 eye = float4(1.0, 1.0, 1.0, 0.0);
     float4 vhalf = normalize(light + eye);
"""
    styleStdin = sci_constants.SCE_C_STDIN
    styleStdout = sci_constants.SCE_C_STDOUT
    styleStderr = sci_constants.SCE_C_STDERR

    def __init__(self):
        # Same as JavaScript's
        KoLanguageBase.__init__(self)
        self._style_info.update(
            _block_comment_styles=[
                sci_constants.SCE_C_COMMENT, sci_constants.SCE_C_COMMENTDOC,
                sci_constants.SCE_C_COMMENTDOCKEYWORD,
                sci_constants.SCE_C_COMMENTDOCKEYWORDERROR
            ],
            _variable_styles=[sci_constants.SCE_C_IDENTIFIER])
        self._setupIndentCheckSoftChar()

    def getVariableStyles(self):
        # Same as JavaScript's
        return self._style_info._variable_styles

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(sci_constants.SCLEX_CPP)
            self._lexer.setKeywords(0, HLSLLangInfo.keywords)
            self._lexer.setProperty('fold.cpp.syntax.based', '1')
            self._lexer.supportsFolding = 1
        return self._lexer
示例#26
0
class koPowerBasicLanguage(KoCommonBasicLanguageService):
    name = "PowerBasic"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{0bc5c569-6546-45ec-8452-4636d326e0f7}"
    _reg_categories_ = [("komodo-language", name)]

    _stateMap = {
        'default': ('SCE_B_DEFAULT', ),
        'keywords': ('SCE_B_KEYWORD', 'SCE_B_KEYWORD2', 'SCE_B_KEYWORD3',
                     'SCE_B_KEYWORD4'),
        'identifiers': ('SCE_B_IDENTIFIER', ),
        'comments': ('SCE_B_COMMENT', ),
        'numbers': ('SCE_B_NUMBER', ),
        'strings': ('SCE_B_STRING', ),
        'stringeol': ('SCE_B_STRINGEOL', ),
        'operators': ('SCE_B_OPERATOR', ),
        'preprocessor': ('SCE_B_PREPROCESSOR', ),
        'date': ('SCE_B_DATE', ),
        'constants': ('SCE_B_CONSTANT', ),
        'assembly': ('SCE_B_ASM', ),
    }
    defaultExtension = '.pb'
    commentDelimiterInfo = {"line": ["rem ", "REM "]}

    sample = """
INPUT "What is your name"; UserName$
PRINT "Hello "; UserName$
DO
   INPUT "How many stars do you want"; NumStars
   Stars$ = ""
   Stars$ = REPEAT$("*", NumStars)   ' <- ANSI BASIC
   --or--
   Stars$ = STRING$(NumStars, "*")   ' <- MS   BASIC
   PRINT Stars$
   DO
      INPUT "Do you want more stars";  Answer$
   LOOP UNTIL Answer$ <> ""
   Answer$ = LEFT$(Answer$, 1);
LOOP WHILE  UCASE$(Answer$) = "Y"
PRINT "Goodbye ";
FOR I = 1 TO 200
   PRINT UserName$; " ";
NEXT I
PRINT
"""

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(
                components.interfaces.ISciMoz.SCLEX_POWERBASIC)
            self._lexer.setKeywords(0, self._keywords_preprocessor + \
                                       self._keywords_functions + \
                                       self._keywords_proceedures + \
                                       self._keywords_datatypes + \
                                       self._keywords_options)
            self._lexer.supportsFolding = 1
        return self._lexer

    _keywords_preprocessor = """$alias $code $com $compile $cpu $debug
        $dim $dynamic $endif $error $event $float $huge $if $include
        $inline $lib $link $optimize $option $segment $sound $stack
        $static $string all array cga chain cntlbreak com ega emulate
        exe fullfloat graph herc iprint lpt map memory none npx off
        path pbdebug procedure signed size speed unit unsigned
        vga""".split()

    _keywords_functions = """absolute access and any append array as
        asc ascend ascii asm at atn attrib base beep bin$ binary bit bits
        bload bsave call case cbcd cbyt cdbl cdwd ceil cext cfix chain
        chdir chdrive chr$ cint circle clear clng close cls codeptr codeseg
        collate color com command$ common cos cqud csng csrlin curdir$ cvb
        cvbyt cvd cvdwd cve cvf cvi cvl cvmd cvms cvq cvs cvwrd cwrd data
        date$ declare decr def defbcd defdbl defext deffix defflx defint
        deflng defqud defsng defstr delay delete descend dim dir$ do draw
        dynamic else elseif ems end endmem environ environ$ eof eqv eradr
        erase erdev erdev$ erl err errnum error errtest execute exit exp
        exp10 exp2 external extract$ far field fileattr files fix fixdigits
        flexchr$ flush fn for frac fre freefile from function get get$
        gosub goto hex$ if imp impabs in incr inkey$ inp input input$
        insert instat instr int interrupt ioctl ioctl$ isfalse istrue
        iterate key kill lbound lcase$ left left$ len let line list loc
        local locate lock lof log log10 log2 loop lpos lprint lset ltrim$
        map max max$ max% mempack memset mid$ min min$ min% mkb$ mkbyt$
        mkd$ mkdir mkdwd$ mke$ mkf$ mki$ mkl$ mkmd$ mkms$ mkq$ mks$ mkwrd$
        mod mtimer multiplex name next not oct$ off on open option or out
        output paint palette peek peek$ peeki peekl pen play pmap point
        poke poke$ pokei pokel popup pos preset print pset public put
        put$ quiet random randomize read redim reg rem remove$ repeat$
        replace reset restore resume return right right$ rmdir rnd rotate
        round rset rtrim$ run scan screen seek seg select setmem sgn
        shared shell shift signed sin sleep sort sound space$ spc sqr
        static step stick stop str$ strig string$ strptr strseg stuff sub
        swap system tab tagarray tally tan then time$ timer to troff tron
        type ubound ucase ucase$ uevent union unlock until using using$
        val varptr varptr$ varseg verify view wait wend while width window
        with write xor""".split()

    _keywords_datatypes = """any bcd byte double dword extended fix flex
        integer long quad single string word""".split()

    _keywords_options = """ascend byval collate delete descend dynamic
        huge local preserve public shared static sort""".split()

    _keywords_proceedures = """arraycalc arrayinfo getstralloc getstrlen
        getstrloc rlsstralloc setonexit setonmempack setuevent pbvbinbase
        pbvcpu pbvcursor1 pbvcursor2 pbvcursorvis pbvdefseg pbverr
        pbvfixdigits pbvflexchr pbvhost pbvminusone pbvnpx pbvone
        pbvrevision pbvrevltr pbvscrnapage pbvscrnbuff pbvscrncard
        pbvscrncols pbvscrnmode pbvscrnpxlattr pbvscrnrows pbvscrntxtattr
        pbvscrnvpage pbvswitch pbvuserarea pbvusingchrs pbvvtxtx1
        pbvvtxtx2 pbvvtxty1 pbvvtxty2 pbvzero""".split()
示例#27
0
class basicBase(KoCommonBasicLanguageService):
    _keywords = None
    _keywords2 = None
    sciMozLexer = None

    commentDelimiterInfo = {
        "line": [ "'",  "rem ", "REM "  ],
    }


    _stateMap = {
        'default': ('SCE_B_DEFAULT',),
        'keywords': ('SCE_B_KEYWORD',
                     'SCE_B_KEYWORD2',
                     'SCE_B_KEYWORD3',
                     'SCE_B_KEYWORD4',),
        'identifiers': ('SCE_B_IDENTIFIER',),
        'comments': ('SCE_B_COMMENT',),
        'numbers': ('SCE_B_NUMBER',),
        'strings': ('SCE_B_STRING',),
        'stringeol': ('SCE_B_STRINGEOL',),
        'operators': ('SCE_B_OPERATOR',),
        'preprocessor': ('SCE_B_PREPROCESSOR',),
        'date': ('SCE_B_DATE',),
        'constants': ('SCE_B_CONSTANT',),
        'assembly': ('SCE_B_ASM',),
        }


    sample = """
INPUT "What is your name"; UserName$
PRINT "Hello "; UserName$
DO
   INPUT "How many stars do you want"; NumStars
   Stars$ = ""
   Stars$ = REPEAT$("*", NumStars)   ' <- ANSI BASIC
   --or--
   Stars$ = STRING$(NumStars, "*")   ' <- MS   BASIC
   PRINT Stars$
   DO
      INPUT "Do you want more stars";  Answer$
   LOOP UNTIL Answer$ <> ""
   Answer$ = LEFT$(Answer$, 1);
LOOP WHILE  UCASE$(Answer$) = "Y"
PRINT "Goodbye ";
FOR I = 1 TO 200
   PRINT UserName$; " ";
NEXT I
PRINT
"""
    
    def __init__(self):
        KoCommonBasicLanguageService.__init__(self)
        del self.matchingSoftChars["'"]
        
    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(self.sciMozLexer)
            self._lexer.setKeywords(0, self._keywords)
            if self._keywords2:
                self._lexer.setKeywords(1, self._keywords2)
            self._lexer.supportsFolding = 1
        return self._lexer
class koPowerBasicLanguage(KoCommonBasicLanguageService):
    name = "PowerBasic"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{0bc5c569-6546-45ec-8452-4636d326e0f7}"
    _reg_categories_ = [("komodo-language", name)]

    _stateMap = {
        'default': ('SCE_B_DEFAULT',),
        'keywords': ('SCE_B_KEYWORD',
                     'SCE_B_KEYWORD2',
                     'SCE_B_KEYWORD3',
                     'SCE_B_KEYWORD4'),
        'identifiers': ('SCE_B_IDENTIFIER',),
        'comments': ('SCE_B_COMMENT',),
        'numbers': ('SCE_B_NUMBER',),
        'strings': ('SCE_B_STRING',),
        'stringeol': ('SCE_B_STRINGEOL',),
        'operators': ('SCE_B_OPERATOR',),
        'preprocessor': ('SCE_B_PREPROCESSOR',),
        'date': ('SCE_B_DATE',),
        'constants': ('SCE_B_CONSTANT',),
        'assembly': ('SCE_B_ASM',),
        }
    defaultExtension = '.pb'
    commentDelimiterInfo = {"line": [ "rem ", "REM " ]}
    
    sample = """
INPUT "What is your name"; UserName$
PRINT "Hello "; UserName$
DO
   INPUT "How many stars do you want"; NumStars
   Stars$ = ""
   Stars$ = REPEAT$("*", NumStars)   ' <- ANSI BASIC
   --or--
   Stars$ = STRING$(NumStars, "*")   ' <- MS   BASIC
   PRINT Stars$
   DO
      INPUT "Do you want more stars";  Answer$
   LOOP UNTIL Answer$ <> ""
   Answer$ = LEFT$(Answer$, 1);
LOOP WHILE  UCASE$(Answer$) = "Y"
PRINT "Goodbye ";
FOR I = 1 TO 200
   PRINT UserName$; " ";
NEXT I
PRINT
"""
    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(
                components.interfaces.ISciMoz.SCLEX_POWERBASIC)
            self._lexer.setKeywords(0, self._keywords_preprocessor + \
                                       self._keywords_functions + \
                                       self._keywords_proceedures + \
                                       self._keywords_datatypes + \
                                       self._keywords_options)
            self._lexer.supportsFolding = 1
        return self._lexer

    _keywords_preprocessor = """$alias $code $com $compile $cpu $debug
        $dim $dynamic $endif $error $event $float $huge $if $include
        $inline $lib $link $optimize $option $segment $sound $stack
        $static $string all array cga chain cntlbreak com ega emulate
        exe fullfloat graph herc iprint lpt map memory none npx off
        path pbdebug procedure signed size speed unit unsigned
        vga""".split()
        
    _keywords_functions = """absolute access and any append array as
        asc ascend ascii asm at atn attrib base beep bin$ binary bit bits
        bload bsave call case cbcd cbyt cdbl cdwd ceil cext cfix chain
        chdir chdrive chr$ cint circle clear clng close cls codeptr codeseg
        collate color com command$ common cos cqud csng csrlin curdir$ cvb
        cvbyt cvd cvdwd cve cvf cvi cvl cvmd cvms cvq cvs cvwrd cwrd data
        date$ declare decr def defbcd defdbl defext deffix defflx defint
        deflng defqud defsng defstr delay delete descend dim dir$ do draw
        dynamic else elseif ems end endmem environ environ$ eof eqv eradr
        erase erdev erdev$ erl err errnum error errtest execute exit exp
        exp10 exp2 external extract$ far field fileattr files fix fixdigits
        flexchr$ flush fn for frac fre freefile from function get get$
        gosub goto hex$ if imp impabs in incr inkey$ inp input input$
        insert instat instr int interrupt ioctl ioctl$ isfalse istrue
        iterate key kill lbound lcase$ left left$ len let line list loc
        local locate lock lof log log10 log2 loop lpos lprint lset ltrim$
        map max max$ max% mempack memset mid$ min min$ min% mkb$ mkbyt$
        mkd$ mkdir mkdwd$ mke$ mkf$ mki$ mkl$ mkmd$ mkms$ mkq$ mks$ mkwrd$
        mod mtimer multiplex name next not oct$ off on open option or out
        output paint palette peek peek$ peeki peekl pen play pmap point
        poke poke$ pokei pokel popup pos preset print pset public put
        put$ quiet random randomize read redim reg rem remove$ repeat$
        replace reset restore resume return right right$ rmdir rnd rotate
        round rset rtrim$ run scan screen seek seg select setmem sgn
        shared shell shift signed sin sleep sort sound space$ spc sqr
        static step stick stop str$ strig string$ strptr strseg stuff sub
        swap system tab tagarray tally tan then time$ timer to troff tron
        type ubound ucase ucase$ uevent union unlock until using using$
        val varptr varptr$ varseg verify view wait wend while width window
        with write xor""".split()
    
    _keywords_datatypes = """any bcd byte double dword extended fix flex
        integer long quad single string word""".split()
    
    _keywords_options = """ascend byval collate delete descend dynamic
        huge local preserve public shared static sort""".split()

    _keywords_proceedures = """arraycalc arrayinfo getstralloc getstrlen
        getstrloc rlsstralloc setonexit setonmempack setuevent pbvbinbase
        pbvcpu pbvcursor1 pbvcursor2 pbvcursorvis pbvdefseg pbverr
        pbvfixdigits pbvflexchr pbvhost pbvminusone pbvnpx pbvone
        pbvrevision pbvrevltr pbvscrnapage pbvscrnbuff pbvscrncard
        pbvscrncols pbvscrnmode pbvscrnpxlattr pbvscrnrows pbvscrntxtattr
        pbvscrnvpage pbvswitch pbvuserarea pbvusingchrs pbvvtxtx1
        pbvvtxtx2 pbvvtxty1 pbvvtxty2 pbvzero""".split()
示例#29
0
class koGoLanguage(KoLanguageBase, KoLanguageBaseDedentMixin):
    name = "Go"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{2d6ed8b6-f079-441a-8b5a-10ef781cb989}"
    _reg_categories_ = [("komodo-language", name)]
    # Copy the base interfaces.
    _com_interfaces_ = KoLanguageBase._com_interfaces_[:]
    # Add koIInterpolationCallback - but it's only available in version 9 and
    # above - so catch the exception for earlier versions.
    try:
        _com_interfaces_.append(components.interfaces.koIInterpolationCallback)
    except:
        log.warn("koIInterpolationCallback does not exist")

    modeNames = ['go']
    primary = 1
    internal = 0
    accessKey = 'g'
    defaultExtension = ".go"
    commentDelimiterInfo = {
        "line": ["//"],
        "block": [("/*", "*/")],
        "markup": "*",
    }
    _dedenting_statements = [u'goto', u'return', u'break', u'continue']

    namedBlockRE = "^[ \t]*?(func\s+(?:\(.*?\)\s*)?\w|package\s+\w)"
    namedBlockDescription = 'Go functions, methods and packages'
    supportsSmartIndent = "brace"
    # The following sample contains embedded tabs because that's the Go way.
    sample = r"""\
package commands

import (
	"encoding/json"
)
type Filters []string
func (f *Filters) String() string {
	a := "a string"
	b := 'c' // a char
	c := 43 // a num
	return fmt.Sprint(*f)
}
/* Block comment
on these two lines */
    """

    def __init__(self):
        KoLanguageBase.__init__(self)
        self._style_info.update(
            _block_comment_styles=[
                sci_constants.SCE_C_COMMENT, sci_constants.SCE_C_COMMENTDOC,
                sci_constants.SCE_C_COMMENTDOCKEYWORD,
                sci_constants.SCE_C_COMMENTDOCKEYWORDERROR
            ],
            _variable_styles=[components.interfaces.ISciMoz.SCE_C_IDENTIFIER])
        self._setupIndentCheckSoftChar()
        self._fastCharData = \
            FastCharData(trigger_char=";",
                         style_list=(sci_constants.SCE_C_OPERATOR,),
                         skippable_chars_by_style={ sci_constants.SCE_C_OPERATOR : "])",},
                         for_check=True)

        # Add extensible items (available in komodo 9 and higher).
        if 'koIInterpolationService' in components.interfaces.keys():
            interpolateSvc = components.classes["@activestate.com/koInterpolationService;1"].\
                                getService(components.interfaces.koIInterpolationService)
            try:
                interpolateSvc.addCode('go', self)
            except Exception:
                log.warn("Unable to add 'go' interpolation shortcut")

    def interpolationCallback(self, code, fileName, lineNum, word, selection,
                              projectFile, prefs):
        if code == 'go':
            golangInfoEx = components.classes["@activestate.com/koAppInfoEx?app=Go;1"].\
                        getService(components.interfaces.koIAppInfoEx)
            return golangInfoEx.executablePath
        raise RuntimeError("Unexpected go code %r" % (code, ))

    def getLanguageService(self, iid):
        return KoLanguageBase.getLanguageService(self, iid)

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CPP)
            self._lexer.supportsFolding = 1
            self._lexer.setProperty('lexer.cpp.allow.dollars', '0')
            self._lexer.setProperty('fold.cpp.syntax.based', '1')
            self._lexer.setProperty('lexer.cpp.backquoted.strings', '1')
            self._lexer.setKeywords(0, GoLangInfo.reserved_keywords)
            # The CPP lexer reserves keywords(2) for comment doc keywords and
            # keywords(3) for "SCE_C_GLOBALCLASS", so treat the
            # predeclared_identifiers (like 'bool') and
            # the predefined_functions (like 'append') as the same.
            other_words = (GoLangInfo.predeclared_identifiers.union(
                GoLangInfo.predeclared_functions))
            self._lexer.setKeywords(1, other_words)
        return self._lexer
示例#30
0
class koGoLanguage(KoLanguageBase, KoLanguageBaseDedentMixin):
    name = "Go"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" % (name)
    _reg_clsid_ = "{2d6ed8b6-f079-441a-8b5a-10ef781cb989}"
    _reg_categories_ = [("komodo-language", name)]
    # Copy the base interfaces.
    _com_interfaces_ = KoLanguageBase._com_interfaces_[:]
    # Add koIInterpolationCallback - but it's only available in version 9 and
    # above - so catch the exception for earlier versions.
    try:
        _com_interfaces_.append(components.interfaces.koIInterpolationCallback)
    except:
        log.warn("koIInterpolationCallback does not exist")

    modeNames = ["go"]
    primary = 1
    internal = 0
    accessKey = "g"
    defaultExtension = ".go"
    commentDelimiterInfo = {"line": ["//"], "block": [("/*", "*/")], "markup": "*"}
    _dedenting_statements = [u"goto", u"return", u"break", u"continue"]

    namedBlockRE = "^[ \t]*?(func\s+(?:\(.*?\)\s*)?\w|package\s+\w)"
    namedBlockDescription = "Go functions, methods and packages"
    supportsSmartIndent = "brace"
    # The following sample contains embedded tabs because that's the Go way.
    sample = r"""\
package commands

import (
	"encoding/json"
)
type Filters []string
func (f *Filters) String() string {
	a := "a string"
	b := 'c' // a char
	c := 43 // a num
	return fmt.Sprint(*f)
}
/* Block comment
on these two lines */
    """

    def __init__(self):
        KoLanguageBase.__init__(self)
        self._style_info.update(
            _block_comment_styles=[
                sci_constants.SCE_C_COMMENT,
                sci_constants.SCE_C_COMMENTDOC,
                sci_constants.SCE_C_COMMENTDOCKEYWORD,
                sci_constants.SCE_C_COMMENTDOCKEYWORDERROR,
            ],
            _variable_styles=[components.interfaces.ISciMoz.SCE_C_IDENTIFIER],
        )
        self._setupIndentCheckSoftChar()
        self._fastCharData = FastCharData(
            trigger_char=";",
            style_list=(sci_constants.SCE_C_OPERATOR,),
            skippable_chars_by_style={sci_constants.SCE_C_OPERATOR: "])"},
            for_check=True,
        )
        # And add the new default prefs if they don't exist
        globalPrefs = (
            components.classes["@activestate.com/koPrefService;1"]
            .getService(components.interfaces.koIPrefService)
            .prefs
        )
        # Chunk adding prefs based on which ones they were added with.
        if not globalPrefs.hasPref("gocodeDefaultLocation"):
            globalPrefs.setStringPref("gocodeDefaultLocation", "")
        if not globalPrefs.hasPref("godefDefaultLocation"):
            globalPrefs.setStringPref("godefDefaultLocation", "")
        if not globalPrefs.hasPref("golangDefaultLocation"):
            globalPrefs.setStringPref("golangDefaultLocation", "")
            globalPrefs.setStringPref("Go/newEncoding", "utf-8")
            globalPrefs.setLongPref("Go/indentWidth", 8)
            globalPrefs.setBooleanPref("Go/useTabs", True)

        # Add the go formatter.
        if not globalPrefs.getBoolean("haveInstalledGoFormatter", False):
            if globalPrefs.hasPref("configuredFormatters"):
                formatters = globalPrefs.getPref("configuredFormatters")
                go_formatter_prefset = components.classes["@activestate.com/koPreferenceSet;1"].createInstance(
                    components.interfaces.koIPreferenceSet
                )
                uuid = "{cf500001-ec59-4047-86e7-369d257f4b80}"
                go_formatter_prefset.id = uuid
                go_formatter_prefset.setStringPref("lang", "Go")
                go_formatter_prefset.setStringPref("name", "GoFmt")
                go_formatter_prefset.setStringPref("uuid", uuid)
                go_formatter_prefset.setStringPref("formatter_name", "generic")
                args_prefset = components.classes["@activestate.com/koPreferenceSet;1"].createInstance(
                    components.interfaces.koIPreferenceSet
                )
                args_prefset.id = "genericFormatterPrefs"
                args_prefset.setStringPref("executable", "%(go)fmt")
                args_prefset.setStringPref("arguments", "-w=false")
                go_formatter_prefset.setPref("genericFormatterPrefs", args_prefset)
                formatters.appendString(uuid)
                globalPrefs.setPref(uuid, go_formatter_prefset)
            globalPrefs.setBoolean("haveInstalledGoFormatter", True)

        # Add extensible items (available in komodo 9 and higher).
        if "koIInterpolationService" in components.interfaces.keys():
            interpolateSvc = components.classes["@activestate.com/koInterpolationService;1"].getService(
                components.interfaces.koIInterpolationService
            )
            try:
                interpolateSvc.addCode("go", self)
            except Exception:
                log.warn("Unable to add 'go' interpolation shortcut")

    def interpolationCallback(self, code, fileName, lineNum, word, selection, projectFile, prefs):
        if code == "go":
            golangInfoEx = components.classes["@activestate.com/koAppInfoEx?app=Go;1"].getService(
                components.interfaces.koIAppInfoEx
            )
            return golangInfoEx.executablePath
        raise RuntimeError("Unexpected go code %r" % (code,))

    def getLanguageService(self, iid):
        return KoLanguageBase.getLanguageService(self, iid)

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CPP)
            self._lexer.supportsFolding = 1
            self._lexer.setProperty("lexer.cpp.allow.dollars", "0")
            self._lexer.setProperty("fold.cpp.syntax.based", "1")
            self._lexer.setProperty("lexer.cpp.backquoted.strings", "1")
            self._lexer.setKeywords(0, GoLangInfo.reserved_keywords)
            # The CPP lexer reserves keywords(2) for comment doc keywords and
            # keywords(3) for "SCE_C_GLOBALCLASS", so treat the
            # predeclared_identifiers (like 'bool') and
            # the predefined_functions (like 'append') as the same.
            other_words = GoLangInfo.predeclared_identifiers.union(GoLangInfo.predeclared_functions)
            self._lexer.setKeywords(1, other_words)
        return self._lexer
示例#31
0
class koLuaLanguage(KoLanguageKeywordBase):
    name = "Lua"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{D3C94E8B-B75C-4fa4-BC4D-986F68ACD33C}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".lua"
    commentDelimiterInfo = {
        "line": [ "--" ],
        "block": [ ("--[[", "]]") ],
    }
    supportsSmartIndent = "keyword"
    _indenting_statements = ['function', 'if', 'for', 'repeat', 'while', 'else',
                             'elseif', 'do']
    _dedenting_statements = ['break', 'return', 'error']
    # These trigger a dedent when entered, but then count +1
    # This might be better than putting 'else' in both
    # _indenting_statements and _keyword_dedenting_keywords
    _keyword_dedenting_keywords = ['end', 'else', 'elseif', 'until']
    
    sample = """require "lfs"

function dirtree(dir)
  assert(dir and dir ~= "", "directory parameter is missing or empty")
  if string.sub(dir, -1) == "/" then
    dir=string.sub(dir, 1, -2)
  end

  local diriters = {lfs.dir(dir)}
  local dirs = {dir}

  return function()
    repeat 
      local entry = diriters[#diriters]()
      if entry then 
        if entry ~= "." and entry ~= ".." then 
          local filename = table.concat(dirs, "/").."/"..entry
          local attr = lfs.attributes(filename)
          if attr.mode == "directory" then 
            table.insert(dirs, entry)
            table.insert(diriters, lfs.dir(filename))
          end
          return filename, attr
        end
      else
        table.remove(dirs)
        table.remove(diriters)
      end
    until #diriters==0
  end
end
    """

    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _block_comment_styles = [sci_constants.SCE_LUA_COMMENTLINE,
                                     sci_constants.SCE_LUA_COMMENTDOC],
            _indent_styles = [sci_constants.SCE_LUA_OPERATOR],
            _variable_styles = [sci_constants.SCE_LUA_IDENTIFIER],
            _lineup_close_styles = [sci_constants.SCE_LUA_OPERATOR],
            _lineup_styles = [sci_constants.SCE_LUA_OPERATOR],
            _keyword_styles = [sci_constants.SCE_LUA_WORD,
                               sci_constants.SCE_LUA_WORD2,
                               sci_constants.SCE_LUA_WORD3,
                               sci_constants.SCE_LUA_WORD4,
                               sci_constants.SCE_LUA_WORD5,
                               sci_constants.SCE_LUA_WORD6,
                               sci_constants.SCE_LUA_WORD7,
                               sci_constants.SCE_LUA_WORD8,
                               ],
            _default_styles = [sci_constants.SCE_LUA_DEFAULT],
            _ignorable_styles = [sci_constants.SCE_LUA_COMMENT,
                                 sci_constants.SCE_LUA_COMMENTLINE,
                                 sci_constants.SCE_LUA_COMMENTDOC,
                                 sci_constants.SCE_LUA_NUMBER],
            )

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_LUA)
            self._lexer.setKeywords(0, self._keywords)
            self._lexer.setKeywords(1, self._keywords1)
            self._lexer.supportsFolding = 1
        return self._lexer

    # Reserved words.
    _keywords = ["and", "break", "do", "else", "elseif", "end", "false", "for", "function",
                 "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then",
                 "true", "until", "while"]
    # Global functions and constants, and libraries.
    _keywords1 = ["assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs",
                  "load", "loadfile", "next", "pairs", "pcall", "print", "rawequal", "rawget",
                  "rawset", "require", "select", "setmetatable", "tonumber", "tostring", "type",
                  "xpcall", "_G", "_VERSION",
                  # New in Lua 5.2.
                  "rawlen", "_ENV",
                  # Deprecated in 5.2.
                  "getfenv", "loadstring", "module", "setfenv", "unpack"
                  
                  "string", "string.byte", "string.char", "string.dump", "string.find",
                  "string.format", "string.gmatch", "string.gsub", "string.len", "string.lower",
                  "string.match", "string.rep", "string.reverse", "string.sub", "string.upper",
                  # New in Lua 5.3.
                  "string.pack", "string.packsize", "string.unpack",

                  "table", "table.concat", "table.insert", "table.remove", "table.sort",
                  # New in 5.2.
                  "table.pack", "table.unpack",
                  # New in in 5.3.
                  "table.move",

                  "math", "math.abs", "math.acos", "math.asin", "math.atan", "math.ceil",
                  "math.cos", "math.deg", "math.exp", "math.floor", "math.fmod", "math.huge",
                  "math.log", "math.max", "math.min", "math.modf", "math.pi", "math.rad",
                  "math.random", "math.randomseed", "math.sin", "math.sqrt", "math.tan",
                  # New in 5.3.
                  "math.maxinteger", "math.mininteger", "math.tointeger", "math.type",
                  "math.ult",

                  "coroutine", "coroutine.create", "coroutine.resume", "coroutine.running",
                  "coroutine.status", "coroutine.wrap", "coroutine.yield",
                  # New in Lua 5.3.
                  "coroutine.isyieldable",

                  "package", "package.cpath", "package.loaded", "package.loadlib",
                  "package.path", "package.preload",
                  # New in 5.2.
                  "package.config", "package.searchers", "package.searchpath",

                  "utf8", "utf8.char", "utf8.charpattern", "utf8.codepoint", "utf8.codes",
                  "utf8.len", "utf8.offset",

                  "io", "io.close", "io.flush", "io.input", "io.lines", "io.open", "io.output",
                  "io.popen", "io.read", "io.stderr", "io.stdin", "io.stdout", "io.tmpfile",
                  "io.type", "io.write",

                  "os", "os.clock", "os.date", "os.difftime", "os.execute", "os.exit",
                  "os.getenv", "os.remove", "os.rename", "os.setlocale", "os.time",
                  "os.tmpname",

                  "debug", "debug.debug", "debug.gethook", "debug.getinfo", "debug.getlocal",
                  "debug.getmetatable", "debug.getregistry", "debug.getupvalue",
                  "debug.sethook", "debug.setlocal", "debug.setmetatable", "debug.setupvalue",
                  "debug.traceback",
                  # New in Lua 5.2.
                  "debug.getuservalue", "debug.setuservalue", "debug.upvalueid",
                  "debug.upvaluejoin"]
    
    #XXX: Override _indentingOrDedentingStatement looking for things like
    #   return function ...
    

    # Override:
    # Handle return ... function differently

    def computeIndent(self, scimoz, indentStyle, continueComments):
        if continueComments:
            return KoLanguageKeywordBase.computeIndent(self, scimoz, indentStyle, continueComments)
        calculatedData = self.getTokenDataForComputeIndent(scimoz, self._style_info)
        indent = self._computeIndent(scimoz, indentStyle, continueComments, self._style_info, calculatedData)
        if indent is not None:
            return indent
        return KoLanguageKeywordBase.computeIndent(self, scimoz, indentStyle, continueComments, calculatedData=calculatedData)

    def _computeIndent(self, scimoz, indentStyle, continueComments, style_info,
                       calculatedData):
        non_ws_tokens = calculatedData['non_ws_tokens']
        if not self._lookingAtReturnFunction(non_ws_tokens, style_info):
            return None
        tok0 = calculatedData['tokens'][0]
        if tok0.style in style_info._default_styles:
            currWSLen = len(tok0.text.expandtabs(scimoz.tabWidth))
            newWSLen = currWSLen + scimoz.indent
        else:
            newWSLen = scimoz.indent
        return scimozindent.makeIndentFromWidth(scimoz, newWSLen)

    def _lookingAtReturnFunction(self, non_ws_tokens, style_info):
        return (len(non_ws_tokens) >= 2
                and non_ws_tokens[0].style in style_info._keyword_styles
                and non_ws_tokens[0].text == "return"
                and non_ws_tokens[1].style in style_info._keyword_styles
                and non_ws_tokens[1].text == "function")
示例#32
0
class koGoLanguage(KoLanguageBase, KoLanguageBaseDedentMixin):
    name = "Go"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{2d6ed8b6-f079-441a-8b5a-10ef781cb989}"
    _reg_categories_ = [("komodo-language", name)]

    modeNames = ['go']
    primary = 1
    internal = 0
    accessKey = 'g'
    defaultExtension = ".go"
    commentDelimiterInfo = {
        "line": [ "//" ],
        "block": [ ("/*", "*/") ],
        "markup": "*",
    }
    _dedenting_statements = [u'goto', u'return', u'break', u'continue']
    
    namedBlockRE = "^[ \t]*?(func\s+(?:\(.*?\)\s*)?\w|package\s+\w)"
    namedBlockDescription = 'Go functions, methods and packages'
    supportsSmartIndent = "brace"
    # The following sample contains embedded tabs because that's the Go way.
    sample = r"""\
package commands

import (
	"encoding/json"
)
type Filters []string
func (f *Filters) String() string {
	a := "a string"
	b := 'c' // a char
	c := 43 // a num
	return fmt.Sprint(*f)
}
/* Block comment
on these two lines */
    """

    def __init__(self):
        KoLanguageBase.__init__(self)
        self._style_info.update(
            _block_comment_styles = [sci_constants.SCE_C_COMMENT,
                                     sci_constants.SCE_C_COMMENTDOC,
                                     sci_constants.SCE_C_COMMENTDOCKEYWORD,
                                     sci_constants.SCE_C_COMMENTDOCKEYWORDERROR],
            _variable_styles = [components.interfaces.ISciMoz.SCE_C_IDENTIFIER]
            )
        self._setupIndentCheckSoftChar()
        self._fastCharData = \
            FastCharData(trigger_char=";",
                         style_list=(sci_constants.SCE_C_OPERATOR,),
                         skippable_chars_by_style={ sci_constants.SCE_C_OPERATOR : "])",},
                         for_check=True)
        # And add the new default prefs if they don't exist
        globalPrefs = components.classes["@activestate.com/koPrefService;1"]\
                          .getService(components.interfaces.koIPrefService).prefs
        # Chunk adding prefs based on which ones they were added with.
        if not globalPrefs.hasPref("gocodeDefaultLocation"):
            globalPrefs.setStringPref("gocodeDefaultLocation", "")
        if not globalPrefs.hasPref("godefDefaultLocation"):
            globalPrefs.setStringPref("godefDefaultLocation", "")
        if not globalPrefs.hasPref("golangDefaultLocation"):
            globalPrefs.setStringPref("golangDefaultLocation", "")
            globalPrefs.setStringPref("Go/newEncoding", "utf-8")
            globalPrefs.setLongPref("Go/indentWidth", 8)
            globalPrefs.setBooleanPref("Go/useTabs", True)
            #TODO: Add formatter prefs along the lines of:
            # <!-- Go formatter -->
            # <preference-set >
            # <string id="formatter_name">generic</string>
            # <string id="lang">Go</string>
            # <string id="name">Go Reformatter</string>
            # <string id="uuid">{286d5b45-a54e-4317-b3c8-da4dc35673a4}</string>
            # </preference-set>


    def getLanguageService(self, iid):
        return KoLanguageBase.getLanguageService(self, iid)

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CPP)
            self._lexer.supportsFolding = 1
            self._lexer.setProperty('lexer.cpp.allow.dollars', '0')
            self._lexer.setProperty('fold.cpp.syntax.based', '1')
            self._lexer.setProperty('lexer.cpp.backquoted.strings', '1')
            self._lexer.setKeywords(0, GoLangInfo.reserved_keywords)
            # The CPP lexer reserves keywords(2) for comment doc keywords and
            # keywords(3) for "SCE_C_GLOBALCLASS", so treat the
            # predeclared_identifiers (like 'bool') and
            # the predefined_functions (like 'append') as the same.
            other_words = (GoLangInfo.predeclared_identifiers.
                           union(GoLangInfo.predeclared_functions))
            self._lexer.setKeywords(1, other_words)
        return self._lexer
示例#33
0
class koErlangLanguage(KoLanguageBase):
    name = "Erlang"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{0153c47a-f668-41d4-8519-9ecd6b1c5ba0}"
    _reg_categories_ = [("komodo-language", name)]

    _stateMap = {
        'default': ('SCE_ERLANG_DEFAULT', ),
        'comments': (
            'SCE_ERLANG_COMMENT',
            'SCE_ERLANG_COMMENT_FUNCTION',
            'SCE_ERLANG_COMMENT_MODULE',
            'SCE_ERLANG_COMMENT_DOC',
            'SCE_ERLANG_COMMENT_DOC_MACRO',
        ),
        'variables': ('SCE_ERLANG_VARIABLE', ),
        'numbers': ('SCE_ERLANG_NUMBER', ),
        'keywords': ('SCE_ERLANG_KEYWORD', ),
        'strings': (
            'SCE_ERLANG_STRING',
            'SCE_ERLANG_CHARACTER',
        ),
        'operators': ('SCE_ERLANG_OPERATOR', ),
        'functions': ('SCE_ERLANG_FUNCTION_NAME', ),
        'macros': ('SCE_ERLANG_MACRO', ),
        'records': ('SCE_ERLANG_RECORD', ),
        'atoms': ('SCE_ERLANG_ATOM', ),
        'nodes': ('SCE_ERLANG_NODE_NAME', ),
        'unknown': ('SCE_ERLANG_UNKNOWN', ),
    }
    defaultExtension = '.erl'
    commentDelimiterInfo = {
        "line": ["%"],
    }

    sample = """-module(test).
-export([fac/1]).

fac(0) -> 1;
fac(N) -> N * fac(N-1).
"""

    def __init__(self):
        KoLanguageBase.__init__(self)
        self._fastCharData = \
            ErlangFastCharData(trigger_char=".",
                         style_list=(sci_constants.SCE_ERLANG_OPERATOR,),
                         skippable_chars_by_style={ sci_constants.SCE_ERLANG_OPERATOR : "])",
                                                    })

    _keywords = """
        after begin case catch cond end fun if let of query receive when
        define record export import include include_lib ifdef ifndef else endif undef
        apply attribute call do in letrec module primop try""".split()

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_ERLANG)
            self._lexer.setKeywords(0, self._keywords)
        return self._lexer
示例#34
0
class koBashLanguage(KoLanguageKeywordBase):
    name = "Bash"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{728daa03-1f7a-4eef-bb7b-de7b322825fa}"
    _reg_categories_ = [("komodo-language", name)]

    _stateMap = {
        'operators': ('SCE_SH_OPERATOR',
                      'SCE_SH_BACKTICKS',),
        'parameters': ('SCE_SH_PARAM',),
        'errors': ('SCE_SH_ERROR',),
        'variables': ('SCE_SH_SCALAR',),
        'default': ('SCE_SH_DEFAULT',),
        'numbers': ('SCE_SH_NUMBER',),
        'identifiers': ('SCE_SH_IDENTIFIER',),
        'strings': ('SCE_SH_CHARACTER',
                    'SCE_SH_STRING',),
        'here documents': ('SCE_SH_HERE_DELIM',
                           'SCE_SH_HERE_Q',),
        'comments': ('SCE_SH_COMMENTLINE',),
        'keywords': ('SCE_SH_WORD',),
        }
    defaultExtension = '.sh'
    commentDelimiterInfo = {"line": [ "#" ],}
    shebangPatterns = [
        re.compile(ur'\A#!.*/(ba)?sh.*$', re.IGNORECASE | re.MULTILINE),
    ]
    
    # Ignore parens due to case statements.
    _lineup_chars = u"{}"
    _lineup_open_chars = "{"
    _lineup_close_chars = "}"

    supportsSmartIndent = "keyword"
    # 'then' is kind of weird, but can be treated just like 'else'
    _indenting_statements = ['if', 'for', 'until', 'while', 'else', 'then', 'do']
    _dedenting_statements = ['break', 'continue', 'return']
    # These trigger a dedent when entered, but then count +1
    # This might be better than putting 'else' in both
    # _indenting_statements and _keyword_dedenting_keywords
    
    # Don't count 'esac' as a dedenter because case stmts need to get
    # indented with ")" and ";;"
    _keyword_dedenting_keywords = ['done', 'fi', 'else', 'then', 'do']
    searchURL = "http://www.gnu.org/software/bash/manual/html_node"
    
    sample = """# build our tags file

find src \( \( -name '*.h' \) -o \\
           \( -name '*.cpp' \) -o \\
           \( -name '*.c' \) -o \\
           \( -name '*.cxx' \) -o \\
            -exec ls -1 `pwd`/{} \; | 
sed -e 's@/cygdrive/c@c:@' -e 's@/\./@/@' | 
perl -n -e 'chomp; printf(qq(%c%c%s,1%c), 12, 10, $_, 10);' > TAGS
"""

    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _indent_styles = [sci_constants.SCE_SH_OPERATOR],
            _variable_styles = [sci_constants.SCE_SH_IDENTIFIER,
                                sci_constants.SCE_SH_SCALAR],
            _lineup_close_styles = [sci_constants.SCE_SH_OPERATOR],
            _lineup_styles = [sci_constants.SCE_SH_OPERATOR],
            _multiline_styles = [sci_constants.SCE_SH_STRING,
                                 sci_constants.SCE_SH_CHARACTER],
            _keyword_styles = [sci_constants.SCE_SH_WORD],
            _default_styles = [sci_constants.SCE_SH_DEFAULT],
            _ignorable_styles = [sci_constants.SCE_SH_ERROR,
                                 sci_constants.SCE_SH_COMMENTLINE,
                                 sci_constants.SCE_SH_NUMBER],
            )

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(sci_constants.SCLEX_BASH)
            self._lexer.setKeywords(0, self.bash_keywords1 + self.bash_keywords2)
            self._lexer.supportsFolding = 1
        return self._lexer

    bash_keywords1="""alias
        ar asa awk banner basename bash bc bdiff break
        bunzip2 bzip2 cal calendar case cat cc cd chmod cksum
        clear cmp col comm compress continue cp cpio crypt
        csplit ctags cut date dc dd declare deroff dev df diff diff3
        dircmp dirname do done du echo ed egrep elif else env
        esac eval ex exec exit expand export expr false fc
        fgrep fi file find fmt fold for function functions
        getconf getopt getopts grep gres hash head help
        history iconv id if in integer jobs join kill local lc
        let line ln logname look ls m4 mail mailx make
        man mkdir more mt mv newgrp nl nm nohup ntps od
        pack paste patch pathchk pax pcat perl pg pr print
        printf ps pwd read readonly red return rev rm rmdir
        sed select set sh shift size sleep sort spell
        split start stop strings strip stty sum suspend
        sync tail tar tee test then time times touch tr
        trap true tsort tty type typeset ulimit umask unalias
        uname uncompress unexpand uniq unpack unset until
        uudecode uuencode vi vim vpax wait wc whence which
        while who wpaste wstart xargs zcat""".split()
    
    bash_keywords2="""chgrp chown chroot dir dircolors
        factor groups hostid install link md5sum mkfifo
        mknod nice pinky printenv ptx readlink seq
        sha1sum shred stat su tac unlink users vdir whoami yes""".split()
示例#35
0
class koHLSLLanguage(KoLanguageBase):
    name = "HLSL"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{fd0846b3-ff7f-41af-b324-179783084469}"
    _reg_categories_ = [("komodo-language", name)]

    primary = 0
    defaultExtension = ".hlsl"
    commentDelimiterInfo = {
        "line": [ "//" ],
        "block": [ ("/*", "*/") ],
        "markup": "*",
    }
    _dedenting_statements = [u'throw', u'return', u'break', u'continue']
    _indenting_statements = [u'case']
    searchURL = "http://www.google.com/search?q=hlsl+site%3Amicrosoft.com%2F+%W"
    # matches:
    # function name
    # name: function
    # name = function
    # class.prototype.name = function
    namedBlockDescription = 'HLSL functions and classes'
    namedBlockRE = r'^[ |\t]*?(?:([\w|\.|_]*?)\s*=\s*function|function\s*([\w|\_]*?)|([\w|\_]*?)\s*:\s*function).*?$'
    supportsSmartIndent = "brace"
    sample = """
     float4 normal = mul(IN.Normal, ModelViewIT);
     normal.w = 0.0;
     normal = normalize(normal);
     float4 light = normalize(LightVec);
     float4 eye = float4(1.0, 1.0, 1.0, 0.0);
     float4 vhalf = normalize(light + eye);
"""
    styleStdin = sci_constants.SCE_C_STDIN
    styleStdout = sci_constants.SCE_C_STDOUT
    styleStderr = sci_constants.SCE_C_STDERR

    def __init__(self):
        # Same as JavaScript's
        KoLanguageBase.__init__(self)
        self._style_info.update(
            _block_comment_styles = [sci_constants.SCE_C_COMMENT,
                                     sci_constants.SCE_C_COMMENTDOC,
                                     sci_constants.SCE_C_COMMENTDOCKEYWORD,
                                     sci_constants.SCE_C_COMMENTDOCKEYWORDERROR],
            _variable_styles = [sci_constants.SCE_C_IDENTIFIER]
            )
        self._setupIndentCheckSoftChar()
        
    def getVariableStyles(self):
        # Same as JavaScript's
        return self._style_info._variable_styles
    
    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(sci_constants.SCLEX_CPP)
            self._lexer.setKeywords(0, HLSLLangInfo.keywords)
            self._lexer.setProperty('fold.cpp.syntax.based', '1')
            self._lexer.supportsFolding = 1
        return self._lexer
示例#36
0
class koLuaLanguage(KoLanguageKeywordBase):
    name = "Lua"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" \
                       % (name)
    _reg_clsid_ = "{D3C94E8B-B75C-4fa4-BC4D-986F68ACD33C}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".lua"
    commentDelimiterInfo = {
        "line": ["--"],
        "block": [("--[[", "]]")],
    }
    supportsSmartIndent = "keyword"
    _indenting_statements = [
        'function', 'if', 'for', 'repeat', 'while', 'else', 'elseif', 'do'
    ]
    _dedenting_statements = ['break', 'return', 'error']
    # These trigger a dedent when entered, but then count +1
    # This might be better than putting 'else' in both
    # _indenting_statements and _keyword_dedenting_keywords
    _keyword_dedenting_keywords = ['end', 'else', 'elseif', 'until']

    sample = """require "lfs"

function dirtree(dir)
  assert(dir and dir ~= "", "directory parameter is missing or empty")
  if string.sub(dir, -1) == "/" then
    dir=string.sub(dir, 1, -2)
  end

  local diriters = {lfs.dir(dir)}
  local dirs = {dir}

  return function()
    repeat 
      local entry = diriters[#diriters]()
      if entry then 
        if entry ~= "." and entry ~= ".." then 
          local filename = table.concat(dirs, "/").."/"..entry
          local attr = lfs.attributes(filename)
          if attr.mode == "directory" then 
            table.insert(dirs, entry)
            table.insert(diriters, lfs.dir(filename))
          end
          return filename, attr
        end
      else
        table.remove(dirs)
        table.remove(diriters)
      end
    until #diriters==0
  end
end
    """

    def __init__(self):
        KoLanguageKeywordBase.__init__(self)
        self._style_info.update(
            _block_comment_styles=[
                sci_constants.SCE_LUA_COMMENTLINE,
                sci_constants.SCE_LUA_COMMENTDOC
            ],
            _indent_styles=[sci_constants.SCE_LUA_OPERATOR],
            _variable_styles=[sci_constants.SCE_LUA_IDENTIFIER],
            _lineup_close_styles=[sci_constants.SCE_LUA_OPERATOR],
            _lineup_styles=[sci_constants.SCE_LUA_OPERATOR],
            _keyword_styles=[
                sci_constants.SCE_LUA_WORD,
                sci_constants.SCE_LUA_WORD2,
                sci_constants.SCE_LUA_WORD3,
                sci_constants.SCE_LUA_WORD4,
                sci_constants.SCE_LUA_WORD5,
                sci_constants.SCE_LUA_WORD6,
                sci_constants.SCE_LUA_WORD7,
                sci_constants.SCE_LUA_WORD8,
            ],
            _default_styles=[sci_constants.SCE_LUA_DEFAULT],
            _ignorable_styles=[
                sci_constants.SCE_LUA_COMMENT,
                sci_constants.SCE_LUA_COMMENTLINE,
                sci_constants.SCE_LUA_COMMENTDOC, sci_constants.SCE_LUA_NUMBER
            ],
        )

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_LUA)
            self._lexer.setKeywords(0, self._keywords)
            self._lexer.setKeywords(1, self._keywords1)
            self._lexer.supportsFolding = 1
        return self._lexer

    # Reserved words.
    _keywords = [
        "and", "break", "do", "else", "elseif", "end", "false", "for",
        "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat",
        "return", "then", "true", "until", "while"
    ]
    # Global functions and constants, and libraries.
    _keywords1 = [
        "assert",
        "collectgarbage",
        "dofile",
        "error",
        "getmetatable",
        "ipairs",
        "load",
        "loadfile",
        "next",
        "pairs",
        "pcall",
        "print",
        "rawequal",
        "rawget",
        "rawset",
        "require",
        "select",
        "setmetatable",
        "tonumber",
        "tostring",
        "type",
        "xpcall",
        "_G",
        "_VERSION",
        # New in Lua 5.2.
        "rawlen",
        "_ENV",
        # Deprecated in 5.2.
        "getfenv",
        "loadstring",
        "module",
        "setfenv",
        "unpack"
        "string",
        "string.byte",
        "string.char",
        "string.dump",
        "string.find",
        "string.format",
        "string.gmatch",
        "string.gsub",
        "string.len",
        "string.lower",
        "string.match",
        "string.rep",
        "string.reverse",
        "string.sub",
        "string.upper",
        # New in Lua 5.3.
        "string.pack",
        "string.packsize",
        "string.unpack",
        "table",
        "table.concat",
        "table.insert",
        "table.remove",
        "table.sort",
        # New in 5.2.
        "table.pack",
        "table.unpack",
        # New in in 5.3.
        "table.move",
        "math",
        "math.abs",
        "math.acos",
        "math.asin",
        "math.atan",
        "math.ceil",
        "math.cos",
        "math.deg",
        "math.exp",
        "math.floor",
        "math.fmod",
        "math.huge",
        "math.log",
        "math.max",
        "math.min",
        "math.modf",
        "math.pi",
        "math.rad",
        "math.random",
        "math.randomseed",
        "math.sin",
        "math.sqrt",
        "math.tan",
        # New in 5.3.
        "math.maxinteger",
        "math.mininteger",
        "math.tointeger",
        "math.type",
        "math.ult",
        "coroutine",
        "coroutine.create",
        "coroutine.resume",
        "coroutine.running",
        "coroutine.status",
        "coroutine.wrap",
        "coroutine.yield",
        # New in Lua 5.3.
        "coroutine.isyieldable",
        "package",
        "package.cpath",
        "package.loaded",
        "package.loadlib",
        "package.path",
        "package.preload",
        # New in 5.2.
        "package.config",
        "package.searchers",
        "package.searchpath",
        "utf8",
        "utf8.char",
        "utf8.charpattern",
        "utf8.codepoint",
        "utf8.codes",
        "utf8.len",
        "utf8.offset",
        "io",
        "io.close",
        "io.flush",
        "io.input",
        "io.lines",
        "io.open",
        "io.output",
        "io.popen",
        "io.read",
        "io.stderr",
        "io.stdin",
        "io.stdout",
        "io.tmpfile",
        "io.type",
        "io.write",
        "os",
        "os.clock",
        "os.date",
        "os.difftime",
        "os.execute",
        "os.exit",
        "os.getenv",
        "os.remove",
        "os.rename",
        "os.setlocale",
        "os.time",
        "os.tmpname",
        "debug",
        "debug.debug",
        "debug.gethook",
        "debug.getinfo",
        "debug.getlocal",
        "debug.getmetatable",
        "debug.getregistry",
        "debug.getupvalue",
        "debug.sethook",
        "debug.setlocal",
        "debug.setmetatable",
        "debug.setupvalue",
        "debug.traceback",
        # New in Lua 5.2.
        "debug.getuservalue",
        "debug.setuservalue",
        "debug.upvalueid",
        "debug.upvaluejoin"
    ]

    #XXX: Override _indentingOrDedentingStatement looking for things like
    #   return function ...

    # Override:
    # Handle return ... function differently

    def computeIndent(self, scimoz, indentStyle, continueComments):
        if continueComments:
            return KoLanguageKeywordBase.computeIndent(self, scimoz,
                                                       indentStyle,
                                                       continueComments)
        calculatedData = self.getTokenDataForComputeIndent(
            scimoz, self._style_info)
        indent = self._computeIndent(scimoz, indentStyle, continueComments,
                                     self._style_info, calculatedData)
        if indent is not None:
            return indent
        return KoLanguageKeywordBase.computeIndent(
            self,
            scimoz,
            indentStyle,
            continueComments,
            calculatedData=calculatedData)

    def _computeIndent(self, scimoz, indentStyle, continueComments, style_info,
                       calculatedData):
        non_ws_tokens = calculatedData['non_ws_tokens']
        if not self._lookingAtReturnFunction(non_ws_tokens, style_info):
            return None
        tok0 = calculatedData['tokens'][0]
        indent = scimoz.indent
        if not indent:
            indent = scimoz.tabWidth  # if 0, Scintilla uses tabWidth
        if tok0.style in style_info._default_styles:
            currWSLen = len(tok0.text.expandtabs(scimoz.tabWidth))
            newWSLen = currWSLen + indent
        else:
            newWSLen = indent
        return scimozindent.makeIndentFromWidth(scimoz, newWSLen)

    def _lookingAtReturnFunction(self, non_ws_tokens, style_info):
        return (len(non_ws_tokens) >= 2
                and non_ws_tokens[0].style in style_info._keyword_styles
                and non_ws_tokens[0].text == "return"
                and non_ws_tokens[1].style in style_info._keyword_styles
                and non_ws_tokens[1].text == "function")
示例#37
0
 def get_lexer(self):
     if self._lexer is None:
         self._lexer = KoLexerLanguageService()
         self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_ERLANG)
         self._lexer.setKeywords(0, self._keywords)
     return self._lexer
示例#38
0
class koCMakeLanguage(KoLanguageBase):
    name = "CMake"
    _reg_desc_ = "%s Language" % name
    _reg_contractid_ = "@activestate.com/koLanguage?language=%s;1" % (name)
    _reg_clsid_ = "{6d6fc84a-1bcf-4dac-af4d-dc5ddde8317b}"
    _reg_categories_ = [("komodo-language", name)]

    defaultExtension = ".cmake"
    commentDelimiterInfo = {
        "line": [ "#" ],
    }

    # Sample file.
    sample = """
set  (PRJ      ${DESKTOP}/common )
set  (FILELIST ${PRJ}/src/source.txt )

message(STATUS "SYSTEM_NAME     : ${CMAKE_SYSTEM_NAME}")

project(project_name)

include_directories(
  ${PRJ}/src
  ${PRJ}/includes
)

# Load SRC Variable from file
file(READ ${FILELIST} SRC)
string(REGEX REPLACE  "#.*$"  ""  SRC  ${SRC})
string(REPLACE        "\n"    ";" SRC  ${SRC})

add_executable(${PROJECT_NAME} ${SRC} )

foreach (f ${SRC})
  set_source_files_properties(${f} PROPERTIES LANGUAGE       CXX)
endforeach(f)
 """

    # Commands:
    cmake_commands = [
        "add_custom_command",
        "add_custom_target",
        "add_definitions",
        "add_dependencies",
        "add_executable",
        "add_library",
        "add_subdirectory",
        "add_test",
        "aux_source_directory",
        "build_command",
        "build_name",
        "cmake_minimum_required",
        "configure_file",
        "create_test_sourcelist",
        "else",
        "elseif",
        "enable_language",
        "enable_testing",
        "endforeach",
        "endif",
        "endmacro",
        "endwhile",
        "exec_program",
        "execute_process",
        "export_library_dependencies",
        "file",
        "find_file",
        "find_library",
        "find_package",
        "find_path",
        "find_program",
        "fltk_wrap_ui",
        "foreach",
        "get_cmake_property",
        "get_directory_property",
        "get_filename_component",
        "get_source_file_property",
        "get_target_property",
        "get_test_property",
        "if",
        "include",
        "include_directories",
        "include_external_msproject",
        "include_regular_expression",
        "install",
        "install_files",
        "install_programs",
        "install_targets",
        "link_directories",
        "link_libraries",
        "list",
        "load_cache",
        "load_command",
        "macro",
        "make_directory",
        "mark_as_advanced",
        "math",
        "message",
        "option",
        "output_required_files",
        "project",
        "qt_wrap_cpp",
        "qt_wrap_ui",
        "remove",
        "remove_definitions",
        "separate_arguments",
        "set",
        "set_directory_properties",
        "set_source_files_properties",
        "set_target_properties",
        "set_tests_properties",
        "site_name",
        "source_group",
        "string",
        "subdir_depends",
        "subdirs",
        "target_link_libraries",
        "try_compile",
        "try_run",
        "use_mangled_mesa",
        "utility_source",
        "variable_requires",
        "vtk_make_instantiator",
        "vtk_wrap_java",
        "vtk_wrap_python",
        "vtk_wrap_tcl",
        "while",
        "write_file",
    ]

    # Variables:
    cmake_variables = [
        "ABSOLUTE",
        "ABSTRACT",
        "ADDITIONAL_MAKE_CLEAN_FILES",
        "ALL",
        "AND",
        "APPEND",
        "ARGS",
        "ASCII",
        "BEFORE",
        "CACHE",
        "CACHE_VARIABLES",
        "CLEAR",
        "COMMAND",
        "COMMANDS",
        "COMMAND_NAME",
        "COMMENT",
        "COMPARE",
        "COMPILE_FLAGS",
        "COPYONLY",
        "DEFINED",
        "DEFINE_SYMBOL",
        "DEPENDS",
        "DOC",
        "EQUAL",
        "ESCAPE_QUOTES",
        "EXCLUDE",
        "EXCLUDE_FROM_ALL",
        "EXISTS",
        "EXPORT_MACRO",
        "EXT",
        "EXTRA_INCLUDE",
        "FATAL_ERROR",
        "FILE",
        "FILES",
        "FORCE",
        "FUNCTION",
        "GENERATED",
        "GLOB",
        "GLOB_RECURSE",
        "GREATER",
        "GROUP_SIZE",
        "HEADER_FILE_ONLY",
        "HEADER_LOCATION",
        "IMMEDIATE",
        "INCLUDES",
        "INCLUDE_DIRECTORIES",
        "INCLUDE_INTERNALS",
        "INCLUDE_REGULAR_EXPRESSION",
        "LESS",
        "LINK_DIRECTORIES",
        "LINK_FLAGS",
        "LOCATION",
        "MACOSX_BUNDLE",
        "MACROS",
        "MAIN_DEPENDENCY",
        "MAKE_DIRECTORY",
        "MATCH",
        "MATCHALL",
        "MATCHES",
        "MODULE",
        "NAME",
        "NAME_WE",
        "NOT",
        "NOTEQUAL",
        "NO_SYSTEM_PATH",
        "OBJECT_DEPENDS",
        "OPTIONAL",
        "OR",
        "OUTPUT",
        "OUTPUT_VARIABLE",
        "PATH",
        "PATHS",
        "POST_BUILD",
        "POST_INSTALL_SCRIPT",
        "PREFIX",
        "PREORDER",
        "PRE_BUILD",
        "PRE_INSTALL_SCRIPT",
        "PRE_LINK",
        "PROGRAM",
        "PROGRAM_ARGS",
        "PROPERTIES",
        "QUIET",
        "RANGE",
        "READ",
        "REGEX",
        "REGULAR_EXPRESSION",
        "REPLACE",
        "REQUIRED",
        "RETURN_VALUE",
        "RUNTIME_DIRECTORY",
        "SEND_ERROR",
        "SHARED",
        "SOURCES",
        "STATIC",
        "STATUS",
        "STREQUAL",
        "STRGREATER",
        "STRLESS",
        "SUFFIX",
        "TARGET",
        "TOLOWER",
        "TOUPPER",
        "VAR",
        "VARIABLES",
        "VERSION",
        "WIN32",
        "WRAP_EXCLUDE",
        "WRITE",
        # Platform specifics.
        "APPLE",
        "MINGW",
        "MSYS",
        "CYGWIN",
        "BORLAND",
        "WATCOM",
        "MSVC",
        "MSVC_IDE",
        "MSVC60",
        "MSVC70",
        "MSVC71",
        "MSVC80",
        "CMAKE_COMPILER_2005",
        "OFF",
        "ON",
    ]

    def get_lexer(self):
        if self._lexer is None:
            # Initialize styling information.
            cmake_style_map = {
                'default': ('SCE_CMAKE_DEFAULT',),
                'comments': ('SCE_CMAKE_COMMENT',),
                'keywords': ('SCE_CMAKE_COMMANDS',),
                'keywords2': ('SCE_CMAKE_PARAMETERS',),
                'variables': ('SCE_CMAKE_VARIABLE', 'SCE_CMAKE_STRINGVAR'),
                'strings': ('SCE_CMAKE_STRINGDQ', 'SCE_CMAKE_STRINGLQ', 'SCE_CMAKE_STRINGRQ'),
                'numbers': ('SCE_CMAKE_NUMBER',),
                'macro': ('SCE_CMAKE_MACRODEF',),
                'section': ('SCE_CMAKE_WHILEDEF', 'SCE_CMAKE_FOREACHDEF', 'SCE_CMAKE_IFDEFINEDEF'),
                'user': ('SCE_CMAKE_USERDEFINED',),
            }
            # Set style mapping.
            import styles
            styles.addSharedStyles(cmake_style_map)
            styles.StateMap[self.name] = cmake_style_map

            # Initalize the lexer.
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(components.interfaces.ISciMoz.SCLEX_CMAKE)
            self._lexer.setKeywords(0, self.cmake_commands)
            self._lexer.setKeywords(1, self.cmake_variables)
        return self._lexer
示例#39
0
class basicBase(KoCommonBasicLanguageService):
    _keywords = None
    _keywords2 = None
    sciMozLexer = None

    commentDelimiterInfo = {
        "line": ["'", "rem ", "REM "],
    }

    _stateMap = {
        'default': ('SCE_B_DEFAULT', ),
        'keywords': (
            'SCE_B_KEYWORD',
            'SCE_B_KEYWORD2',
            'SCE_B_KEYWORD3',
            'SCE_B_KEYWORD4',
        ),
        'identifiers': ('SCE_B_IDENTIFIER', ),
        'comments': ('SCE_B_COMMENT', ),
        'numbers': ('SCE_B_NUMBER', ),
        'strings': ('SCE_B_STRING', ),
        'stringeol': ('SCE_B_STRINGEOL', ),
        'operators': ('SCE_B_OPERATOR', ),
        'preprocessor': ('SCE_B_PREPROCESSOR', ),
        'date': ('SCE_B_DATE', ),
        'constants': ('SCE_B_CONSTANT', ),
        'assembly': ('SCE_B_ASM', ),
    }

    sample = """
INPUT "What is your name"; UserName$
PRINT "Hello "; UserName$
DO
   INPUT "How many stars do you want"; NumStars
   Stars$ = ""
   Stars$ = REPEAT$("*", NumStars)   ' <- ANSI BASIC
   --or--
   Stars$ = STRING$(NumStars, "*")   ' <- MS   BASIC
   PRINT Stars$
   DO
      INPUT "Do you want more stars";  Answer$
   LOOP UNTIL Answer$ <> ""
   Answer$ = LEFT$(Answer$, 1);
LOOP WHILE  UCASE$(Answer$) = "Y"
PRINT "Goodbye ";
FOR I = 1 TO 200
   PRINT UserName$; " ";
NEXT I
PRINT
"""

    def __init__(self):
        KoCommonBasicLanguageService.__init__(self)
        del self.matchingSoftChars["'"]

    def get_lexer(self):
        if self._lexer is None:
            self._lexer = KoLexerLanguageService()
            self._lexer.setLexer(self.sciMozLexer)
            self._lexer.setKeywords(0, self._keywords)
            if self._keywords2:
                self._lexer.setKeywords(1, self._keywords2)
            self._lexer.supportsFolding = 1
        return self._lexer