how to use tern in codemirror to add my special text for every word in my editor? - codemirror

I want to use tern (to add type for every word in my own language ) so I add to my html page this :
<link rel="stylesheet" href="plugin/codemirror/addon/tern/tern.css">
<link rel="stylesheet" href="plugin/codemirror/addon/dialog/dialog.css">
<script src="plugin/codemirror/addon/tern/tern.js"></script>
<script src="plugin/codemirror/addon/dialog/dialog.js"></script>
what I try :
I try alot But nothing work :( ,
I try to write :
"Ctrl-I": function(cm) { CodeMirror.tern.getServer(cm).showType(cm); }, but not work
and I try to write like demo:
<script>
function getURL(url, c) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status < 400) return c(null, xhr.responseText);
var e = new Error(xhr.responseText || "No response");
e.status = xhr.status;
c(e);
};
}
var server;
getURL("//ternjs.net/defs/ecma5.json", function(err, code) {
if (err) throw new Error("Request for ecma5.json: " + err);
server = new CodeMirror.TernServer({defs: [JSON.parse(code)]});
editor.setOption("extraKeys", {
"Ctrl-Space": function(cm) { server.complete(cm); },
"Ctrl-I": function(cm) { server.showType(cm); },
"Ctrl-O": function(cm) { server.showDocs(cm); },
"Alt-.": function(cm) { server.jumpToDef(cm); },
"Alt-,": function(cm) { server.jumpBack(cm); },
"Ctrl-Q": function(cm) { server.rename(cm); },
"Ctrl-.": function(cm) { server.selectName(cm); }
})
editor.on("cursorActivity", function(cm) { server.updateArgHints(cm); });
});
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "javascript"
});
But nothing work
so can any body help me what functions I must to call to add my own tern to my own words ???

Related

Show HTML in window with OK button in VSCode extension

I need to insert text after the cursor if the user agrees. I can't find anything in the documentation for my task.
Mission of my extension:
user writes code
then he calls the extension
it sends all code to a server
returns and shows some code in an additional window with an "OK" button
pressing the "OK" button inserts the server's response after the cursor
I have a problem with point 4. I can't find a method to show the additional window with an "OK" button.
All code from extension.js:
function activate(context) {
console.log('"showText" active');
const commandId = 'extension.showText'
let disposable = vscode.commands.registerCommand(commandId, function () {
const text = editor.document.getText()
let options = {
method: 'GET',
uri: 'http://example.com:8081/',
body: {
text: text
},
json: true
}
rp(options)
.then(function (respString) {
console.log(respString);
// what should I call here?
// vscode.window.showInformationMessage(respString);
})
.catch(function(err) {
console.log(err);
});
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {
console.log('showText disactive');
}
module.exports = {
activate,
deactivate
}
It is not duplicate of How to handle click event in Visual Studio Code message box? because I need HTML page. And this decision just shows text message with confim button.
My decision is:
webview-sample
Webview API
My example:
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const workspace = vscode.workspace;
const window = vscode.window;
const rp = require("request-promise");
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
/**
* #param {vscode.ExtensionContext} context
*/
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Extension activated');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const commandId = 'extension.showText'
let disposable = vscode.commands.registerCommand(commandId, function () {
const editor = window.activeTextEditor;
const text = editor.document.getText();
console.log('For editor "'+ editor._id +'"');
let options = {
method: 'POST',
uri: URL,
body: {
text: text
},
json: true
};
rp(options)
.then(function (res) { // res
const panel = window.createWebviewPanel(
'type_id', // Identifies the type of the webview. Used internally
'Title', // Title of the panel displayed to the user
vscode.ViewColumn.Two, // Editor column to show the new webview panel in.
{
// Enable scripts in the webview
enableScripts: true
} // Webview options. More on these later.
);
panel.webview.html = res;
// Handle messages from the webview
// закрывать когда выбираешь другое окошко
window.onDidChangeActiveTextEditor(
ev => {
// console.log(ev._id, editor._id, editor);
ev && ev._id && ev._id != editor._id && panel.dispose();
}
)
// закрывать когда закрываешь окно
workspace.onDidCloseTextDocument(
textDocument => {
console.log("closed => " + textDocument.isClosed)
panel.dispose();
},
null,
context.subscriptions
);
// любая клавиша кроме enter - фильтр по префиксу
// если enter - поиск подсказок
workspace.onDidChangeTextDocument(
ev => {
console.log(ev);
if (ev && ev.contentChanges && ev.contentChanges.length
&& (ev.contentChanges[0].text || ev.contentChanges[0].rangeLength)) {
// do smth
} else {
console.error('No changes detected. But it must be.', ev);
}
},
null,
context.subscriptions
);
panel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case 'use':
console.log('use');
editor.edit(edit => {
let pos = new vscode.Position(editor.selection.start.line,
editor.selection.start.character)
edit.insert(pos, message.text);
panel.dispose()
});
return;
case 'hide':
panel.dispose()
console.log('hide');
return;
}
},
undefined,
context.subscriptions
);
panel.onDidDispose(
() => {
console.log('disposed');
},
null,
context.subscriptions
)
})
.catch(function(err) {
console.log(err);
});
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
console.log('Extension disactivated');
}
module.exports = {
activate,
deactivate
}
The example of res:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</head>
<body>
<p id="text">Text</p>
<button onclick="useAdvise()">Use</button>
<button onclick="hideAdvise()">Hide</button>
<script>
const vscode = acquireVsCodeApi();
function useAdvise(){
let text_ = $(document).find("#text").text();
vscode.postMessage({command: 'use',text: text_})
}
function hideAdvise(){
vscode.postMessage({command: 'hide'})
}
</script>
</body>
</html>

Facing issue as 404 while Ajax call in typo3

I am new in typo3 and used the ajaxselectlist extension but while the time usage I am facing 404 not found an error.
Below code is fetch from ajaxselectlist/Resources/Templates/OptionRecord/List.html
<script>
jQuery(document).ready(function ($) {
var form = $('#ajaxselectlist-form');
var selectForm = $('.ajaxFormOption');
var controllerpath = $("#uri_hidden").val();
var resultContainer = $('#ajaxCallResult');
var service = {
ajaxCall: function (data) {
console.log("---->"+data.serialize());
$.ajax({
url: controllerpath,
cache: false,
data: {'uid':'1'},
success: function (result) {
resultContainer.html(result).fadeIn('slow');
},
error: function (jqXHR, textStatus, errorThrow) {
resultContainer.html('Ajax request - ' + textStatus + ': ' + errorThrow).fadeIn('fast');
}
});
}
};
form.submit(function (ev) {
ev.preventDefault();
service.ajaxCall($(this));
});
selectForm.change(function () {
resultContainer.fadeOut('slow');
form.submit();
});
selectForm.trigger('change');
});
</script>

How to reuse jquery-ui-autocomplete cached results when appending search term?

I have the following JS method to bind the jQuery UI autocomplete widget to a search text box. Everything works fine, including caching, except that I make unnecessary server calls when appending my search term because I don't reuse the just-retrieved results.
For example, searching for "ab" fetches some results from the server. Typing "c" after "ab" in the search box fetches "abc" results from the server, instead of reusing the cached "ab" results and omitting ones that don't match "abc".
I went down the path of manually looking up the "ab" search results, filtering them using a regex to select the "abc" subset, but this totally seems like I'm reinventing the wheel. What is the proper, canonical way to tell the widget to use the "ab" results, but filter them for the "abc" term and redisplay the shortened dropdown?
function bindSearchForm() {
"use strict";
var cache = new Object();
$('#search_text_field').autocomplete({
minLength: 2,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.ajax({type: 'POST',
dataType: 'json',
url: '/get_search_data',
data: {q: term},
success: function (data) {
cache[term] = data;
response(data);
}
});
});
}
Here's my "brute-force, reinventing the wheel" method, which is, for now, looking like the right solution.
function bindSearchForm() {
"use strict";
var cache = new Object();
var terms = new Array();
function cacheNewTerm(newTerm, results) {
// maintain a 10-term cache
if (terms.push(newTerm) > 10) {
delete cache[terms.shift()];
}
cache[newTerm] = results;
};
$('#search_text_field').autocomplete({
minLength: 2,
source: function (request, response) {
var term = request.term.toLowerCase();
if (term in cache) {
response(cache[term]);
return;
} else if (terms.length) {
var lastTerm = terms[terms.length - 1];
if (term.substring(0, lastTerm.length) === lastTerm) {
var results = new Array();
for (var i = 0; i < cache[lastTerm].length; i++) {
if (cache[lastTerm][i].label.toLowerCase().indexOf(term) !== -1) {
results.push(cache[lastTerm][i]);
}
}
response(results);
return;
}
}
$.ajax({type: 'POST',
dataType: 'json',
url: '/get_search_data',
data: {q: term},
success: function (data) {
cacheNewTerm(term, data);
response(data);
return;
}
});
});
}
If anyone wants a version that supports multiple entries in the text box then please see below:
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
var cache = new Object();
var terms = new Array();
function cacheNewTerm(newTerm, results) {
// keep cache of 10 terms
if (terms.push(newTerm) > 10) {
delete cache[terms.shift()];
}
cache[newTerm] = results;
}
$("#searchTextField")
.on("keydown",
function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).autocomplete("instance").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
source: function (request, response) {
var term = extractLast(request.term.toLowerCase());
if (term in cache) {
response(cache[term]);
return;
} else if (terms.length) {
var lastTerm = terms[terms.length - 1];
console.log('LAst Term: ' + lastTerm);
if (term.substring(0, lastTerm.length) === lastTerm) {
var results = new Array();
for (var i = 0; i < cache[lastTerm].length; i++) {
console.log('Total cache[lastTerm[.length] = ' +
cache[lastTerm].length +
'....' +
i +
'-' +
lastTerm[i]);
console.log('Label-' + cache[lastTerm][i]);
var cachedItem = cache[lastTerm][i];
if (cachedItem != null) {
if (cachedItem.toLowerCase().indexOf(term) !== -1) {
results.push(cache[lastTerm][i]);
}
}
}
response(results);
return;
}
}
$.ajax({
url: '#Url.Action("GetSearchData", "Home")',
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
term: extractLast(request.term)
},
success: function (data) {
cacheNewTerm(term, data);
response($.map(data,
function (item) {
return {
label: item
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
search: function () {
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});

File Format for Phonegap [duplicate]

I'm trying to work with files on IOS, using Phonegap[cordova 1.7.0].
I read how to access files and read them on the API Documentation of phone gap. But I don't know, when the file is read where will it be written ? & How can I output the text, image, or whatever the text is containing on the iPhone screen?
Here's the code I'm using:
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
As of Cordova 3.5 (at least), FileReader objects only accept File objects, not FileEntry objects (I'm not sure about prior releases).
Here's an example that will output the contents a local file readme.txt to the console. The difference here from Sana's example is the call to FileEntry.file(...). This will provide the File object needed for the call to the FileReader.readAs functions.
function readFile() {
window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile('readme.txt',
{create: false, exclusive: false}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new window.FileReader();
reader.onloadend = function(evt) {console.log(evt.target.result);};
reader.onerror = function(evt) {console.log(evt.target.result);};
reader.readAsText(file);
}, function(e){console.log(e);});
}, function(e){console.log(e);});
}, function(e) {console.log(e);});
}
That's what worked for me in case anyone needs it:
function ReadFile() {
var onSuccess = function (fileEntry) {
var reader = new FileReader();
reader.onloadend = function (evt) {
console.log("read success");
console.log(evt.target.result);
document.getElementById('file_status').innerHTML = evt.target.result;
};
reader.onerror = function (evt) {
console.log("read error");
console.log(evt.target.result);
document.getElementById('file_status').innerHTML = "read error: " + evt.target.error;
};
reader.readAsText(fileEntry); // Use reader.readAsURL to read it as a link not text.
};
console.log("Start getting entry");
getEntry(true, onSuccess, { create: false });
};
If you are using phonegap(Cordova) 1.7.0, following page will work in iOS, replace following template in index.html
<!DOCTYPE html>
<html>
<head>
<title>FileWriter Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample text'");
writer.truncate(11);
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample'");
writer.seek(4);
writer.write(" different text");
writer.onwriteend = function(evt){
console.log("contents of file now 'some different text'");
}
};
};
writer.write("some sample text");
}
function fail(error) {
console.log(error.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Write File</p>
</body>
</html>

Childbrowser plugin not working in Phonegap

I'm using Backbone, Require and Underscore Bundled with Phonegap or Cordova.
I tried using the childbrowser plugin but it wont work. I followed the instructions here.
http://blog.digitalbackcountry.com/2012/03/installing-the-childbrowser-plugin-for-ios-with-phonegapcordova-1-5/
define([
'jquery',
'backbone',
'underscore',
'base64',
'mobile',
'const',
'child',
'text!template/login/login.tpl.html'
],function($, Backbone, _, base64, Mobile, Const, ChildBrowser, template){
var EncodeAuth = function(user,pass)
{
var _tok = user + ':' + pass;
var _hash = Base64.encode(_tok);
return "Basic "+ _hash;
}
var LoginView = Backbone.View.extend({
events:{
"click .login-btn" : "Login",
"click .connection-btn" : "OpenSite"
},
initialize: function(){
},
Login: function(){
Const.USERNAME = $("#username").val();
Const.PASSWORD = $("#password").val();
if(!Const.USERNAME || !Const.PASSWORD)
{
navigator.notification.alert("Invalid Username/Password!");
$("input").val("");
}else{
var auth = EncodeAuth(Const.USERNAME,Const.PASSWORD);
var sendAuthorization = function (xhr) {
xhr.setRequestHeader('Authorization', auth)
};
this.model.save(this.model, {
beforeSend : sendAuthorization,
success: function(model,result){
if(result.ErrorMessage === null)
{
alert(JSON.stringify(result.Message));
$("input").val("");
}
else
{
alert(JSON.stringify(result.ErrorMessage));
$("input").val("");
}
},
error: function(model,result){
alert("Remote server returned an error. Not Found");
$("input").val("");
}
});
}
},
OpenSite: function(){
window.plugins.ChildBrowser.showWebPage("http://www.google.com");
}
});
return LoginView;
});
Any ideas?