完善代码补全功能

This commit is contained in:
fofolee 2022-03-31 17:25:05 +08:00
parent 17cf743e1f
commit f6b8bb2a8d
21 changed files with 1273 additions and 18 deletions

11
src/api/importAll.js Normal file
View File

@ -0,0 +1,11 @@
const importAll = context => {
const map = {}
for (const key of context.keys()) {
const keyArr = key.split('/')
keyArr.shift()
map[keyArr.join('.').replace(/\.js$/g, '')] = context(key)
}
return map
}
export default importAll

View File

@ -1,4 +1,3 @@
<script type="text/javascript">
const programs = { const programs = {
quickcommand: { quickcommand: {
name: "quickcommand", name: "quickcommand",
@ -101,7 +100,4 @@ const programs = {
color: "#438eff", color: "#438eff",
}, },
}; };
export default { export default programs
programs,
};
</script>

View File

@ -5,11 +5,17 @@
<script> <script>
import * as monaco from "monaco-editor"; import * as monaco from "monaco-editor";
import { toRaw } from "vue"; import { toRaw } from "vue";
import utoolsApi from "!raw-loader!../types/utools.api.d.ts"; import importAll from "../api/importAll.js";
import quickcommandApi from "!raw-loader!../types/quickcommand.api.d.ts";
import electronApi from "!raw-loader!../types/electron.d.ts"; //
import nodeApi from "!raw-loader!../types/node.api.d.ts"; let apis = importAll(
import commonApi from "!raw-loader!../types/common.d.ts"; require.context("!raw-loader!../plugins/monaco/types/", false, /\.ts$/)
);
//
let languageCompletions = importAll(
require.context("../plugins/monaco/completions/", false, /\.js$/)
);
export default { export default {
data() { data() {
@ -36,6 +42,10 @@ export default {
}, },
} }
); );
this.loadTypes();
this.registerLanguage();
},
loadTypes() {
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({ monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true, noSemanticValidation: true,
noSyntaxValidation: false, noSyntaxValidation: false,
@ -46,11 +56,82 @@ export default {
allowJs: true, allowJs: true,
lib: [], lib: [],
}); });
//
monaco.languages.typescript.javascriptDefaults.addExtraLib( monaco.languages.typescript.javascriptDefaults.addExtraLib(
quickcommandApi + utoolsApi + electronApi + nodeApi + commonApi, Object.values(apis)
.map((x) => x.default)
.join("\n"),
"api.d.ts" "api.d.ts"
); );
}, },
registerLanguage() {
let that = this;
const identifierPattern = "([a-zA-Z_]\\w*)";
let getTokens = (code) => {
let identifier = new RegExp(identifierPattern, "g");
let tokens = [];
let array1;
while ((array1 = identifier.exec(code)) !== null) {
tokens.push(array1[0]);
}
return Array.from(new Set(tokens));
};
let createDependencyProposals = (range, keyWords, editor, curWord) => {
let keys = [];
let tokens = getTokens(editor.getModel().getValue());
//
for (const item of tokens) {
if (item != curWord.word) {
keys.push({
label: item,
kind: monaco.languages.CompletionItemKind.Text,
documentation: "",
insertText: item,
range: range,
});
}
}
//
Object.keys(keyWords).forEach((ItemKind) => {
keyWords[ItemKind].forEach((item) => {
keys.push({
label: item,
kind: monaco.languages.CompletionItemKind[ItemKind],
documentation: "",
insertText: item,
range: range,
});
});
});
return keys;
};
// applescript
monaco.languages.register({
id: "applescript",
});
//
Object.keys(languageCompletions).forEach((language) => {
monaco.languages.registerCompletionItemProvider(language, {
provideCompletionItems: function (model, position) {
var word = model.getWordUntilPosition(position);
var range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn,
};
return {
suggestions: createDependencyProposals(
range,
languageCompletions[language].default,
toRaw(that.editor),
word
),
};
},
});
});
},
getEditorValue() { getEditorValue() {
return toRaw(this.editor).getValue(); return toRaw(this.editor).getValue();
}, },

View File

@ -127,14 +127,14 @@
</template> </template>
<script> <script>
import globalVars from "components/GlobalVars"; import allProgrammings from "../api/programs.js";
import MonocaEditor from "components/MonocaEditor"; import MonocaEditor from "components/MonocaEditor";
export default { export default {
components: { MonocaEditor }, components: { MonocaEditor },
data() { data() {
return { return {
options: Object.keys(globalVars.programs), options: Object.keys(allProgrammings),
program: "quickcommand", program: "quickcommand",
customOptions: { bin: "", argv: "", ext: "" }, customOptions: { bin: "", argv: "", ext: "" },
scptarg: "", scptarg: "",
@ -166,7 +166,7 @@ export default {
}); });
}, },
matchLanguage() { matchLanguage() {
let language = Object.values(globalVars.programs).filter( let language = Object.values(allProgrammings).filter(
(program) => program.ext === this.customOptions.ext (program) => program.ext === this.customOptions.ext
); );
if (language.length) { if (language.length) {
@ -174,7 +174,7 @@ export default {
} }
}, },
setLanguage(language) { setLanguage(language) {
let highlight = globalVars.programs[language].highlight; let highlight = allProgrammings[language].highlight;
this.$refs.editor.setEditorLanguage(highlight ? highlight : language); this.$refs.editor.setEditorLanguage(highlight ? highlight : language);
}, },
showHelp() { showHelp() {
@ -216,7 +216,7 @@ export default {
this.showRunResult(stdout, raw, true); this.showRunResult(stdout, raw, true);
}); });
} else { } else {
let option = globalVars.programs[this.program]; let option = allProgrammings[this.program];
if (this.program === "custom") if (this.program === "custom")
option = { option = {
bin: this.customOptions.bin, bin: this.customOptions.bin,

View File

@ -0,0 +1,8 @@
var Text = ["AppleScript", "false", "linefeed", "return", "pi", "quote", "result", "space", "tab", "true", ];
var Keyword = ["about", "above", "after", "against", "and", "around", "as", "at", "back", "before", "beginning", "behind", "below", "beneath", "beside", "between", "but", "by", "considering", "contain", "contains", "continue", "copy", "div", "does", "eighth", "else", "end", "equal", "equals", "error", "every", "exit", "fifth", "first", "for", "fourth", "from", "front", "get", "given", "global", "if", "ignoring", "in", "into", "is", "it", "its", "last", "local", "me", "middle", "mod", "my", "ninth", "not", "of", "on", "onto", "or", "over", "prop", "property", "put", "ref", "reference", "repeat", "returning", "script", "second", "set", "seventh", "since", "sixth", "some", "tell", "tenth", "that", "the", "then", "third", "through", "thru", "timeout", "times", "to", "transaction", "try", "until", "where", "while", "whose", "with", "without", "alias", "application", "boolean", "class", "constant", "date", "file", "integer", "list", "number", "real", "record", "string", "text", "character", "characters", "contents", "day", "frontmost", "id", "item", "length", "month", "name", "paragraph", "paragraphs", "rest", "reverse", "running", "time", "version", "weekday", "word", "words", "year"];
var Function = ["activate", "beep", "count", "delay", "launch", "log", "offset", "read", "round", "run", "say", "summarize", "write", "clipboard info", "the clipboard", "info for", "list disks", "list folder", "mount volume", "path to", "close for access", "open for access", "get eof", "set eof", "current date", "do shell script", "get volume settings", "random number", "set volume", "system attribute", "system info", "time to GMT", "load script", "run script", "store script", "scripting components", "ASCII character", "ASCII number", "localized string", "folder", "from list", "remote application", "URL", "display alert", "display dialog", ];
export default {
Keyword,
Function,
Text,
};

View File

@ -0,0 +1,8 @@
var Text = ["true", "false"];
var Keyword = "goto|call|exit|break|exist|defined|errorlevel|cmdextversion|if|else|for|EQU|NEQ|LSS|LEQ|GTR|GEQ".split("|");
var Function = "assoc|bcdedit|cd|chcp|chdir|cls|color|copy|date|del|dir|echo|endlocal|erase|format|ftype|graftabl|md|mkdir|mklink|mode|more|move|path|pause|popd|prompt|pushd|rd|rem|ren|rename|rmdir|robocopy|set|setlocal|shift|start|time|title|tree|type|ver|verify|vol|wmic".split("|");
export default {
Text,
Keyword,
Function,
};

View File

@ -0,0 +1,6 @@
var Keywords = "auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile inline restrict asm fortran".split(" ")
var Struct = "int long char short double float unsigned signed void bool".split(" ")
export default {
Keywords,
Struct
}

View File

@ -0,0 +1,11 @@
var Keyword = "abstract as async await base break case catch checked class const continue" + " default delegate do else enum event explicit extern finally fixed for" + " foreach goto if implicit in interface internal is lock namespace new" + " operator out override params private protected public readonly ref return sealed" + " sizeof stackalloc static struct switch this throw try typeof unchecked" + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + " global group into join let orderby partial remove select set value var yield" + "catch class do else finally for foreach if struct switch try while" + "class interface namespace struct var"
var Struct = "Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + " UInt64 bool byte char decimal double short int long object" + " sbyte float string ushort uint ulong"
var Text = "true false null"
Keyword = Keyword.split(" ")
Struct = Struct.split(" ")
Text = Text.split(" ")
export default {
Keyword,
Struct,
Text
}

View File

@ -0,0 +1,6 @@
var Function = ["_G", "_VERSION", "assert", "collectgarbage", "dofile", "error", "getfenv", "getmetatable", "ipairs", "load", "loadfile", "loadstring", "module", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawset", "require", "select", "setfenv", "setmetatable", "tonumber", "tostring", "type", "unpack", "xpcall", "coroutine.create", "coroutine.resume", "coroutine.running", "coroutine.status", "coroutine.wrap", "coroutine.yield", "debug.debug", "debug.getfenv", "debug.gethook", "debug.getinfo", "debug.getlocal", "debug.getmetatable", "debug.getregistry", "debug.getupvalue", "debug.setfenv", "debug.sethook", "debug.setlocal", "debug.setmetatable", "debug.setupvalue", "debug.traceback", "close", "flush", "lines", "read", "seek", "setvbuf", "write", "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", "math.abs", "math.acos", "math.asin", "math.atan", "math.atan2", "math.ceil", "math.cos", "math.cosh", "math.deg", "math.exp", "math.floor", "math.fmod", "math.frexp", "math.huge", "math.ldexp", "math.log", "math.log10", "math.max", "math.min", "math.modf", "math.pi", "math.pow", "math.rad", "math.random", "math.randomseed", "math.sin", "math.sinh", "math.sqrt", "math.tan", "math.tanh", "os.clock", "os.date", "os.difftime", "os.execute", "os.exit", "os.getenv", "os.remove", "os.rename", "os.setlocale", "os.time", "os.tmpname", "package.cpath", "package.loaded", "package.loaders", "package.loadlib", "package.path", "package.preload", "package.seeall", "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", "table.concat", "table.insert", "table.maxn", "table.remove", "table.sort"];
var Keyword = ["and", "break", "elseif", "false", "nil", "not", "or", "return", "true", "function", "end", "if", "then", "else", "do", "while", "repeat", "until", "for", "in", "local"];
export default {
Function,
Keyword
}

View File

@ -0,0 +1,10 @@
var Function = ["abs", "accept", "alarm", "atan2", "bind", "binmode", "bless", "bootstrap", "break", "caller", "chdir", "chmod", "chomp", "chop", "chown", "chr", "chroot", "close", "closedir", "connect", "cos", "crypt", "dbmclose", "dbmopen", "default", "defined", "delete", "die", "do", "dump", "each", "endgrent", "endhostent", "endnetent", "endprotoent", "endpwent", "endservent", "eof", "eval", "exec", "exists", "exit", "exp", "fcntl", "fileno", "flock", "fork", "format", "formline", "getc", "getgrent", "getgrgid", "getgrnam", "gethostbyaddr", "gethostbyname", "gethostent", "getlogin", "getnetbyaddr", "getnetbyname", "getnetent", "getpeername", "getpgrp", "getppid", "getpriority", "getprotobyname", "getprotobynumber", "getprotoent", "getpwent", "getpwnam", "getpwuid", "getservbyname", "getservbyport", "getservent", "getsockname", "getsockopt", "given", "glob", "gmtime", "goto", "grep", "hex", "import", "index", "int", "ioctl", "join", "keys", "kill", "last", "lc", "lcfirst", "length", "link", "listen", "localtime", "lock", "log", "lstat", "map", "mkdir", "msgctl", "msgget", "msgrcv", "msgsnd", "new", "next", "no", "oct", "open", "opendir", "ord", "pack", "package", "pipe", "pop", "pos", "print", "printf", "prototype", "push", "rand", "read", "readdir", "readline", "readlink", "readpipe", "recv", "redo", "ref", "rename", "require", "reset", "return", "reverse", "rewinddir", "rindex", "rmdir", "say", "scalar", "seek", "seekdir", "select", "semctl", "semget", "semop", "send", "setgrent", "sethostent", "setnetent", "setpgrp", "setpriority", "setprotoent", "setpwent", "setservent", "setsockopt", "shift", "shmctl", "shmget", "shmread", "shmwrite", "shutdown", "sin", "sleep", "socket", "socketpair", "sort", "splice", "split", "sprintf", "sqrt", "srand", "stat", "state", "study", "sub", "substr", "symlink", "syscall", "sysopen", "sysread", "sysseek", "system", "syswrite", "tell", "telldir", "tie", "tied", "time", "times", "truncate", "uc", "ucfirst", "umask", "undef", "unlink", "unpack", "unshift", "untie", "use", "utime", "values", "vec", "wait", "waitpid", "wantarray", "warn", "when", "write"]
var Keyword = ["local", "my", "our"]
var Operator = ["lt", "gt", "le", "ge", "eq", "ne", "cmp", "not", "and", "or", "xor"]
var Variable = ["STDIN", "STDIN_TOP", "STDOUT", "STDOUT_TOP", "STDERR", "STDERR_TOP", "$ARG", "$_", "@ARG", "@_", "$LIST_SEPARATOR", "$\"", "$PROCESS_ID", "$PID", "$$", "$REAL_GROUP_ID", "$GID", "$(", "$EFFECTIVE_GROUP_ID", "$EGID", "$)", "$PROGRAM_NAME", "$0", "$SUBSCRIPT_SEPARATOR", "$SUBSEP", "$;", "$REAL_USER_ID", "$UID", "$<", "$EFFECTIVE_USER_ID", "$EUID", "$>", "$a", "$b", "$COMPILING", "$^C", "$DEBUGGING", "$^D", "${^ENCODING}", "$ENV", "%ENV", "$SYSTEM_FD_MAX", "$^F", "@F", "${^GLOBAL_PHASE}", "$^H", "%^H", "@INC", "%INC", "$INPLACE_EDIT", "$^I", "$^M", "$OSNAME", "$^O", "${^OPEN}", "$PERLDB", "$^P", "$SIG", "%SIG", "$BASETIME", "$^T", "${^TAINT}", "${^UNICODE}", "${^UTF8CACHE}", "${^UTF8LOCALE}", "$PERL_VERSION", "$^V", "${^WIN32_SLOPPY_STAT}", "$EXECUTABLE_NAME", "$^X", "$1", "$MATCH", "$&", "${^MATCH}", "$PREMATCH", "$`", "${^PREMATCH}", "$POSTMATCH", "$'", "${^POSTMATCH}", "$LAST_PAREN_MATCH", "$+", "$LAST_SUBMATCH_RESULT", "$^N", "@LAST_MATCH_END", "@+", "%LAST_PAREN_MATCH", "%+", "@LAST_MATCH_START", "@-", "%LAST_MATCH_START", "%-", "$LAST_REGEXP_CODE_RESULT", "$^R", "${^RE_DEBUG_FLAGS}", "${^RE_TRIE_MAXBUF}", "$ARGV", "@ARGV", "ARGV", "ARGVOUT", "$OUTPUT_FIELD_SEPARATOR", "$OFS", "$,", "$INPUT_LINE_NUMBER", "$NR", "$.", "$INPUT_RECORD_SEPARATOR", "$RS", "$/", "$OUTPUT_RECORD_SEPARATOR", "$ORS", "$\\", "$OUTPUT_AUTOFLUSH", "$|", "$ACCUMULATOR", "$^A", "$FORMAT_FORMFEED", "$^L", "$FORMAT_PAGE_NUMBER", "$%", "$FORMAT_LINES_LEFT", "$-", "$FORMAT_LINE_BREAK_CHARACTERS", "$:", "$FORMAT_LINES_PER_PAGE", "$=", "$FORMAT_TOP_NAME", "$^", "$FORMAT_NAME", "$~", "${^CHILD_ERROR_NATIVE}", "$EXTENDED_OS_ERROR", "$^E", "$EXCEPTIONS_BEING_CAUGHT", "$^S", "$WARNING", "$^W", "${^WARNING_BITS}", "$OS_ERROR", "$ERRNO", "$!", "%OS_ERROR", "%ERRNO", "%!", "$CHILD_ERROR", "$?", "$EVAL_ERROR", "$@", "$OFMT", "$#", "$*", "$ARRAY_BASE", "$[", "$OLD_PERL_VERSION", "$]"]
export default {
Function,
Keyword,
Operator,
Variable
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,11 @@
var Keyword = ["as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "lambda", "pass", "raise", "return", "try", "while", "with", "yield", "in", "nonlocal", "False", "True", "None", "async", "await", ];
var Function = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr", "hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow", "property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__", "NotImplemented", "Ellipsis", "__debug__", "ascii", "bytes", "exec", "print", ];
var Operator = ["and", "or", "not", "is"];
var Text = ["True", "False"]
export default {
Keyword,
Function,
Operator,
Text
};

View File

@ -0,0 +1,4 @@
var Keyword = ["alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc", "caller", "lambda", "proc", "public", "protected", "private", "require", "load", "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__", "def", "class", "case", "for", "while", "until", "module", "then", "catch", "loop", "proc", "begin", "end", "until", ];
export default {
Keyword
};

View File

@ -0,0 +1,8 @@
var Keyword = ["if", "then", "do", "else", "elif", "while", "until", "for", "in", "esac", "fi", "fin", "fil", "done", "exit", "set", "unset", "export", "function", ];
var Function = "ab|awk|bash|beep|cat|cc|cd|chown|chmod|chroot|clear|cp|curl|cut|diff|echo|find|gawk|gcc|get|git|grep|hg|kill|killall|ln|ls|make|mkdir|openssl|mv|nc|nl|node|npm|ping|ps|restart|rm|rmdir|sed|service|sh|shopt|shred|source|sort|sleep|ssh|start|stop|su|sudo|svn|tee|telnet|top|touch|vi|vim|wall|wc|wget|who|write|yes|zsh".split("|");
var Text = ["true", "false"];
export default {
Keyword,
Function,
Text,
};

View File

@ -85,8 +85,8 @@ declare function fetch(
// console // console
declare var console: { declare var console: {
log(message?: any, ...optionalParams: any[]): void, log(message?: any): void,
error(message?: any, ...optionalParams: any[]): void error(message?: any): void
} }
// process // process

1069
src/plugins/monaco/types/lib.es5.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff