Example #1
0
async function toggleProxy() {

    const httpProxy: IHTTP_ProxyConf = getHttpProxy();

    // let settingsTmpDir = (process.platform == 'win32' ? process.env.TMP : process.env.TMPDIR);
    let settingsTmpDir = os.tmpdir();
    let settingsTmpFile = path.join(settingsTmpDir, path.basename(settingsPath + '.tmp.' + Math.random()));

    // debug
    // console.log(settingsTmpDir);
    // console.log(settingsTmpFile);

    let line: string;
    let array = await fs.readFileSync(settingsPath, 'utf8').toString().split("\n");

    // Backup to extensionPath
    let backupTmpFile = path.join(vscode.extensions.getExtension("satokaz.vscode-toggleproxy").extensionPath, path.basename(settingsPath + '.tmp'));
    if(fs.statSync(settingsPath).size !== 0){
        await fs.writeFileSync(backupTmpFile, array.join('\n'));
    }

    for (line in array) {
        const matchResult = regExpMatchHttpProxy(array[line]);

        // console.log('matchResult =', matchResult)

        if (matchResult !== null) {
            if (!matchResult.http_proxyEnabled) {
                // should enable proxy
                array[line] = array[line].replace(/\/\/\W/, "");
                vscode.window.setStatusBarMessage('Enabled http.proxy', 2000);
            } else {
                // should disable proxy
                array[line] = array[line].replace(/^/, "// ");
                vscode.window.setStatusBarMessage('Disabled http.proxy', 2000);
            }
        }
    }

    await fs.writeFileSync(settingsTmpFile, array.join('\n'));
    // copy tmp settings file to vscode settings
    // console.log("fs.writeFileSync(settingsPath, fs.readFileSync(settingsTmpFile,\"utf-8\"), 'utf8');")
    await fs.writeFileSync(settingsPath, await fs.readFileSync(settingsTmpFile,"utf-8"));
    // console.log("fs.unlink(settingsTmpFile);");
    await fs.unlink(settingsTmpFile);

    // node-notifier
    if (vscode.workspace.getConfiguration('toggleproxy')['notifier'] === true) {
            notifier.notify({
            'title': 'Visual Studio Code - Proxy Notification',
            'message': !httpProxy.http_proxyEnabled ? 'Proxy Enabled: ' + httpProxy.http_proxy : 'Proxy Disabled',
            'appName': 'Visual Studio Code',
            'icon': path.join(vscode.extensions.getExtension("satokaz.vscode-toggleproxy").extensionPath, path.join('images', 'octicon-globe_128_0_7c05c9_none.png')) ,
            timeout: 5
        });
    }
    vscode.workspace.onDidChangeConfiguration(e => configureHttpRequest());
    return void 0;
}
    async function testCompletion(fileToTest: string, testCases: Array<[vscode.Position, string[]]>) {
        const casesPath = path.join(rootDir!, 'fixtures', 'e2e-cases', fileToTest);
        const ext = vscode.extensions.getExtension('wix.stylable-intelligence');
        let testDoc: vscode.TextDocument;

        if (ext) {
            const doc = await vscode.workspace.openTextDocument(casesPath);
            testDoc = doc;
            await vscode.window.showTextDocument(testDoc);
            await ext.activate();

            return Promise.all(testCases.map(async ([position, expected]) => {
                const list = await vscode.commands.executeCommand<vscode.CompletionList>(
                    'vscode.executeCompletionItemProvider',
                    testDoc.uri,
                    position
                );
                const labels = list!.items.map(x => x.label);
                for (const entry of expected) {
                    if (!~labels.indexOf(entry)) {
                        assert.fail('', entry, 'missing expected item in completion list', '');
                    }
                }
            }));
        } else {
            throw new Error('Where is my extension?!!');
        }
    }
export async function getExtension() {
  const cmt = vscode.extensions.getExtension<CMakeTools>('vector-of-bool.cmake-tools');
  if (!cmt) {
    throw new Error('Extension doesn\'t exist');
  }
  return cmt.isActive ? Promise.resolve(cmt.exports) : cmt.activate();
}
Example #4
0
export function activate(context: vscode.ExtensionContext): any {

    const extensionId = 'ms-vscode.csharp';
    const extension = vscode.extensions.getExtension(extensionId);
    const extensionVersion = extension.packageJSON.version;
    const aiKey = extension.packageJSON.contributes.debuggers[0].aiKey;
    const reporter = new TelemetryReporter(extensionId, extensionVersion, aiKey);

    util.setExtensionPath(extension.extensionPath);

    _channel = vscode.window.createOutputChannel('C#');

    let logger = new Logger(text => _channel.append(text));

    ensureRuntimeDependencies(extension, logger, reporter)
        .then(() => {
            // activate language services
            OmniSharp.activate(context, reporter);

            // register JSON completion & hover providers for project.json
            context.subscriptions.push(addJSONProviders());
            
            // activate coreclr-debug
            coreclrdebug.activate(context, reporter, logger, _channel);
        });
}
Example #5
0
export function setup(context: ExtensionContext, entries: [Entry])
{
  update_entries(entries)

  const prettify_symbols_mode =
    extensions.getExtension<PrettifySymbolsMode>("siegebell.prettify-symbols-mode")
  if (prettify_symbols_mode) {
    prettify_symbols_mode.activate().then(() =>
    {
      const substitutions = [] as [Substitution]
      for (const entry of names) {
        const sym = entry[0]
        substitutions.push(
          {
            ugly: library.escape_regex(sym),
            pretty: library.escape_regex(get_unicode(sym))
          })
      }
      for (const language of ["isabelle", "isabelle-ml", "isabelle-output"]) {
        context.subscriptions.push(
          prettify_symbols_mode.exports.registerSubstitutions(
            {
              language: language,
              substitutions: substitutions
            }))
      }
    })
  }
  else {
    window.showWarningMessage("Please install extension \"Prettify Symbols Model\" and restart!")
  }
}
export function thisExtension() {
  const ext = vscode.extensions.getExtension('vector-of-bool.cmake-tools');
  if (!ext) {
    throw new Error('Out own extension is null! What gives?');
  }
  return ext;
}
Example #7
0
export async function activate(context: vscode.ExtensionContext) {
  const formatter = new HTMLDocumentFormatter();
  context.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider('nornj', formatter));

  const extension = vscode.extensions.getExtension(typeScriptExtensionId);
  if (!extension) {
    return;
  }

  await extension.activate();
  if (!extension.exports || !extension.exports.getAPI) {
    return;
  }
  const api = extension.exports.getAPI(0);
  if (!api) {
    return;
  }

  vscode.workspace.onDidChangeConfiguration(
    e => {
      if (e.affectsConfiguration(configurationSection)) {
        synchronizeConfiguration(api);
      }
    },
    undefined,
    context.subscriptions
  );

  synchronizeConfiguration(api);
}
Example #8
0
async function getRenderedSourceCode(): Promise<string> {
  let printConfig = vscode.workspace.getConfiguration("print", null);
  let printAndClose = printConfig.printAndClose ? " onload = \"window.print();window.close();\"" : "";
  if (printConfig.renderMarkdown && commandArgs.fsPath.split('.').pop().toLowerCase() === "md") {
    let markdownConfig = vscode.workspace.getConfiguration("markdown", null);
    return `<!DOCTYPE html><html><head><title>${commandArgs.fsPath}</title>
    <meta charset="utf-8"/>
    <style>
    html, body {
      font-family: ${markdownConfig.preview.fontFamily};
      font-size: ${markdownConfig.preview.fontSize}px;
      line-height: ${markdownConfig.preview.lineHeight}em;
    }
    img {
      max-width: 100%;
    }
    h1,h2,h3,h4,h5,h6 {
      page-break-after:avoid;
      page-break-inside:avoid;
    }
    </style>
    ${markdownConfig.styles.map((cssFilename: string) => `<link href="${cssFilename}" rel="stylesheet" />`).join("\n")}
    </head>
    <body${printAndClose}>${markdown_it().render(fs.readFileSync(commandArgs.fsPath).toString())}</body></html>`;
  }
  let x = vscode.extensions.getExtension("pdconsec.vscode-print");
  if (!x) { throw new Error("Cannot resolve extension. Has the name changed? It is defined by the publisher and the extension name defined in package.json"); }
  let stylePath = `${x.extensionPath}/node_modules/highlight.js/styles`;
  let defaultCss = getFileText(`${stylePath}/default.css`);
  let swatchCss = getFileText(`${stylePath}/${printConfig.colourScheme}.css`);
  let sourceCode = await getSourceCode();
  let renderedCode = "";
  try {
    renderedCode = hljs.highlight(sourceCode[0], sourceCode[1]).value;
  }
  catch (err) {
    renderedCode = hljs.highlightAuto(sourceCode[1]).value;
  }
  var addLineNumbers = printConfig.lineNumbers === "on" || (printConfig.lineNumbers === "inherit" && vscode.window.activeTextEditor && (vscode.window.activeTextEditor.options.lineNumbers || 0) > 0);
  if (addLineNumbers) {
    var startLine = selection && !(selection.isEmpty || selection.isSingleLine) ? selection.start.line + 1 : 1;
    renderedCode = renderedCode
      .split("\n")
      .map((line, i) => `<tr><td class="line-number">${startLine + i}</td><td class="line-text">${line}</td></tr>`)
      .join("\n")
      .replace("\n</td>", "</td>")
      ;
  } else {
    renderedCode = renderedCode
      .split("\n")
      .map((line, i) => `<tr><td class="line-text">${line}</td></tr>`)
      .join("\n")
      .replace("\n</td>", "</td>")
      ;
  }
  let editorConfig = vscode.workspace.getConfiguration("print", null);
  let html = `<html><head><title>${commandArgs.fsPath}</title><style>body{margin:0;padding:0;tab-size:${editorConfig.tabSize}}\n${defaultCss}\r${swatchCss}\n${lineNumberCss.replace("{lineSpacing}", (printConfig.lineSpacing - 1).toString())}\n.hljs { max-width:100%; width:100%; font-family: Consolas, monospace; font-size: ${printConfig.fontSize}; }\n</style></head><body${printAndClose}><table class="hljs">${renderedCode}</table></body></html>`;
  return html;
}
Example #9
0
    start() {
        let projectPath: string = "";
        if(vscode.workspace.rootPath !== undefined) {
            projectPath = path.join(vscode.workspace.rootPath);
        } else {
            const savedFiles: vscode.TextDocument[] = vscode.workspace.textDocuments.filter((value) => {
                return value.uri.scheme === 'file';
            });
            if(savedFiles.length > 0) {
                projectPath = path.dirname(savedFiles[0].fileName);
            } else {
                // Bail out, lets use our extensionPath as projectPath
                projectPath = vscode.extensions.getExtension("mjmcloug.vscode-elixir").extensionPath;
            }
        }
        const optionsWin = { cwd: projectPath, windowsVerbatimArguments: true, stdio: 'pipe' };
        const optionsUnix = { cwd: projectPath, stdio: 'pipe' };
        if (process.platform === 'win32') {
            this.p = cp.spawn('cmd', ['/s', '/c', '"' + [this.command].concat(this.args).concat(this.env).join(' ') + '"'], optionsWin);
        }
        else {
            this.p = cp.spawn(this.command, this.args.concat(this.env), optionsUnix);
        }
        console.log('[vscode-elixir] server started', this.p);
        this.p.on('message', (message) => {
            console.log('message', message);
        });
        this.p.on('error', (error) => {
            console.log('[vscode-elixir]', error.toString());
        });
        this.p.on('close', (exitCode) => {
            console.log('[vscode-elixir] exited', exitCode);
        });
        this.p.stdout.on('data', (chunk) => {
            if (chunk.indexOf(`END-OF-${this.lastRequestType}`) > -1) {
                const chunkString: string = chunk.toString();
                const splitStrings: string[] = chunkString.split(`END-OF-${this.lastRequestType}`);
                const result = (this.buffer + splitStrings[0]).trim();
                this.resultCallback(result);
                this.buffer = '';
                this.busy = false;
            } else {
                this.buffer += chunk.toString();
            }
        });
        this.p.stderr.on('data', (chunk: Buffer) => {
            const errorString = chunk.toString();
            if (!errorString.startsWith('Initializing')) {
                console.log('[vscode-elixir] error: arboting command', chunk.toString());
                //TODO: this could be handled better.
                this.resultCallback('');
                this.busy = false;

            } else {
                console.log('[vscode-elixir]', chunk.toString());
                this.ready = true;
            }
        });
    }
Example #10
0
 constructor() {
     const extensionPath: string = vscode.extensions.getExtension("mjmcloug.vscode-elixir").extensionPath;
     this.command = 'elixir';
     this.args = [path.join(extensionPath, 'alchemist-server/run.exs')];
     this.env = 'dev';
     this.buffer = '';
     this.busy = false;
 }