How being able to recognize javascript in codemirror? - javascript

I am creating a website in which I am trying to embed code blocks. Someone referred me to the CodeMirror library and thereafter I am trying to have some Javascript code in a code block .
I have incorporated the CodeMirror CSS and JS libraries into my HTMl
file and have created an instance of CodeMirror.
I managed to create a code block. But the code block doesn't apply any formatting/styling to the text in regards to whether it is Javascript or not
It just shows a code block with plain text. I have till now implemented the following code.
At the beginning I defined the following lines:
<link rel="stylesheet" href="codemirror-5.47.0/lib/codemirror.css">
<script src="codemirror-5.47.0/lib/codemirror.js"></script>
<script type="text/javascript" language="javascript">
window.load = function () {
var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("codeeditor"), {
mode: "javascript",
lineNumbers: true
});
myCodeMirror.setSize(500, 300);
}
</script>
<textarea id="codeeditor" rows="20" cols="100">
var GetArray = function (Feature) {var dic = { "Bedrijfsvestigingen": ["bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_ALandbouw_BosbouwEnVisserij", "bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_B-fNijverheidEnEnergie", "bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_G_p_IHandelEnHoreca", "bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_H_p_JVervoer_InformatieEnCommunicatie", "bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_K-lFinancieleDiensten_OnroerendGoed", "bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_M-nZakelijkeDienstverlening", "bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_R-uCultuur_Recreatie_OverigeDiensten", "bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenTotaal"]};
</textarea>
The result is thus a code block with plain text and thus not formatting have been applied on JavaScript code. In case someone knows a solution to this problem, it would be nice to have a pure Javascript solution, since for example I am not familiar with jQuery for example.

You seem to have forgotten to import the "mode"-file; and probably some addons.
var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("codeeditor"), {
mode: "javascript",
lineNumbers: true
});
//myCodeMirror.setSize(500, 300);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.47.0/codemirror.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.47.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.47.0/mode/javascript/javascript.min.js"></script>
<textarea id="codeeditor" rows="20" cols="100">
var GetArray = function(Feature) {
var dic = {
"Bedrijfsvestigingen": [
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_ALandbouw_BosbouwEnVisserij",
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_B-fNijverheidEnEnergie",
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_G_p_IHandelEnHoreca",
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_H_p_JVervoer_InformatieEnCommunicatie",
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_K-lFinancieleDiensten_OnroerendGoed",
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_M-nZakelijkeDienstverlening",
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenNaarActiviteit_R-uCultuur_Recreatie_OverigeDiensten",
"bedrijfsvestigingen_Sbi2008_BedrijfsvestigingenTotaal"
]
};
}
</textarea>

Related

Relative line numbers for monaco editor

Monaco Editor offers VIM key bindings. I also want to make the line numbers relative when using the VIM mode. Is there any API in the monaco global object which I can use to achieve this?
Note: I don't own the code base. I want to use this in a website that already has a monaco editor instance.
I went through the global object and could not find anything useful.
[
"create",
"onDidCreateEditor",
"createDiffEditor",
"createDiffNavigator",
"createModel",
"setModelLanguage",
"setModelMarkers",
"getModelMarkers",
"onDidChangeMarkers",
"getModels",
"getModel",
"onDidCreateModel",
"onWillDisposeModel",
"onDidChangeModelLanguage",
"createWebWorker",
"colorizeElement",
"colorize",
"colorizeModelLine",
"tokenize",
"defineTheme",
"setTheme",
"remeasureFonts",
"registerCommand",
"AccessibilitySupport",
"ContentWidgetPositionPreference",
"CursorChangeReason",
"DefaultEndOfLine",
"EditorAutoIndentStrategy",
"EditorOption",
"EndOfLinePreference",
"EndOfLineSequence",
"MinimapPosition",
"MouseTargetType",
"OverlayWidgetPositionPreference",
"OverviewRulerLane",
"RenderLineNumbersType",
"RenderMinimap",
"ScrollbarVisibility",
"ScrollType",
"TextEditorCursorBlinkingStyle",
"TextEditorCursorStyle",
"TrackedRangeStickiness",
"WrappingIndent",
"InjectedTextCursorStops",
"PositionAffinity",
"ConfigurationChangedEvent",
"BareFontInfo",
"FontInfo",
"TextModelResolvedOptions",
"FindMatch",
"ApplyUpdateResult",
"EditorType",
"EditorOptions"
]
Simply set lineNumbers to "relative".
monaco.editor.create(document.getElementById('container'), {
value: `function x() {
console.log("Hello world!");
}`,
language: 'javascript',
theme: 'vs-dark',
lineNumbers: 'relative'
});
<link rel="stylesheet" data-name="vs/editor/editor.main" href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.26.1/min/vs/editor/editor.main.min.css">
<div id="container" style="height:400px;border:1px solid black;"></div>
<script>var require = { paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.26.1/min/vs' } }</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.26.1/min/vs/loader.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.26.1/min/vs/editor/editor.main.nls.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.26.1/min/vs/editor/editor.main.js"></script>
Given that you want to dynamically change the options and you probably don't have access to the editor instance, you can find the active editors on the page using the global monaco object with monaco.editor.getEditors(), which returns an array of all active instances, then use updateOptions() to customize the line numbers.
In your case it'd look something like:
// anywhere in the JS code
monaco.editor.getEditors()[0].updateOptions({
lineNumbers: 'relative'
});

Does Depreciated version of JQuery Compat Edge mean this code will not run?

I am having trouble getting JQuery to initialize my code when the document is ready. The developer mode in Chrome runs the code without any flags, but nothing loads either. The original author used JQuery Compat Edge, which officially was never released. Does this matter?
The code I am using came from http://jsfiddle.net/Tfs2M/2/. I researched here and here and found many people have problems with their code loading. JQuery does a great job with that so I made what i thought were appropriate modifications. I noticed though the author used Compact Edge. This was a cutting edge version of JQuery about 3 years ago no longer in use. I figured JQuery 3.2.1 would suffice, this is what I came up with.
function starter(GRASP) { //removed $ reference and added a func name.
var GRID_ROWS,
GRID_COLS,
GRID_ELEMENT;
GRASP.config = {
gridContainer: "grid",
matrixContainer: "matrix",
matrixHeader: "matrixHeader"
};
GRASP.start = function () {
GRID_ROWS = $("#rows").val();
GRID_COLS = $("#cols").val();
createGrid();
};
function createGrid() {
//Love to know what the # is doing
GRID_ELEMENT = $("#" + GRASP.config.gridContainer);
var cell; // Contains the 1 or 0 based upon the cell selection
var newGrid = $('<div id="grid" class="gridContainer" ></div>');
//add cells to grid top to bottom with class 'cell and hover attribute
for (var i = 1; i <= GRID_ROWS; i++) {
for (var j = 1; j <= GRID_COLS; j++) {
$("<div class='cell' data-hover-text='"+i+","+j+"'>0</div>")
.appendTo(newGrid);
newGrid.on('click', '.cell', cellClick);
}
}
newGrid.height(38 * GRID_ROWS);
newGrid.width(38 * GRID_COLS);
//add all the new cells to GRID_ELEMENT
GRID_ELEMENT.replaceWith(newGrid);
}
//Changes contents of a cell from 0 to 1, fancy if else statement
function cellClick() {
$(this).text($(this).text() == "0" ? "1" : "0");
}
} // removed the null, false, undefined code since I was using JQuery
I also added the following JQuery too.
$(document).ready(function () {
starter();
});
Here is the HTML if this is of any use.
<html>
<head>
<link rel="stylesheet" type="text/css" href="Coordinate Plane.css">
<script type="text/javascript" src="Coordinate Plane.js"></script>
<script src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="Coordinate PlaneJQ.js">
</head>
<body>
<div id="gridLayout" class="gridLayout">
<div id="gridHeader">
<h2>Aperture Configuration:</h2>
Grid Size:
<input id="rows" type="number" min="1" max="50" value="10" width="40"
size="3" onChange="GRASP.start();"/>x
<input id="cols" type="number" min="1" max="50" value="10"
width="40" size="3" onChange="GRASP.start();"/>
</div>
<div id="grid" class="gridContainer"></div>
</div>
</body>
</html>
Posts like this get voted down, I have made about 3 programs in Javascript so far. If there is a more appropriate site for beginners, please leave a note in the comments.
Thank you!
Your script does not run as-is without throwing console errors. The reason is that you've "half-converted" the code from the Fiddle you references (incompletely, with various problems) from an Immediately-Invoked Function "Class" to, well, what you've got here.
Problem #1 is that GRASP is not defined, because of the way you've modified the last portion of the IIFE.
Adding this somewhere before you call starter() solves that problem.
window.GRASP = {};
Problem #2 is that you set up function starter(GRASP) to accept the variable GRASP to be passed in, but you don't pass it in, so it's still undefined inside the function. I have removed that, and made it simply function starter().
Here is a working Fiddle with your code, updated to work properly.

Syntax highlighting for C code in Orion text editor embedded in HTML

I'm trying to get C syntax highlighting get to work for my HTML app.
I'm embedding Orion editor. For now only JavaScript syntax highlighting is working, but I think it should be possible to get C highlighting as well, because the git repository at https://github.com/eclipse/orion/tree/master/editor/releases/latest/stylers features "stylers" also for Java and C.
Here's my setup code:
<link rel="stylesheet" type="text/css" href="http://eclipse.org/orion/editor/releases/latest/built-editor.css"/>
<script src="http://eclipse.org/orion/editor/releases/latest/built-editor.js"></script>
<script>
if (window.addEventListener) {
window.addEventListener('load', function() {
require(["orion/editor/edit"], function(edit) {
edit({className: "editor"});
});
}, false);
}
</script>
<style>
pre.editor{
padding: 0px;
border: 1px solid lightgrey;
}
</style>
This markup code successfully creates an edit box with JavaScript highlighting:
<pre class="editor" data-editor-lang="js">
// JavaScript
function() { }
</pre>
Here's the code for C that's not working (the data-editor-lang="c" attribute is a guess, cannot find documentation for this):
<pre class="editor" data-editor-lang="c">
// C/C++
int main() {
volatile float x = 12.f;
}
</pre>
Here's Java version (but it works if I change orion/editor/releases/latest/ to orion/editor/releases/5.0/):
<pre class="editor" data-editor-lang="java">
// Java
class X extends Y {}
</pre>
I get these error messages when I test this HTML:
Error: undefined missing orion/editor/stylers/c/syntax built-editor.js:297
Error: undefined missing orion/editor/stylers/text_x-java-source/syntax built-editor.js:297
After some trial and error I got syntax highlighting for javascript working when using only the Orion client. Same strategy might work for you:
requirejs.config({
baseUrl : '.',
paths: {
'orion/editor': 'lib/orion',
'jquery': 'bower_components/jquery/dist/jquery.min'
}
});
-
require(['orion/editor/built-editor', 'orion/editor/stylers/application_javascript/syntax'], function(edit, syntax) {
var deferred = new $.Deferred();
deferred.resolve(syntax);
edit({
className: "editor",
lang:'js',
grammarProvider: function(){
return deferred.promise();
}
});
});
Another option might be to use built-codeEdit instead of build-editor for the client. Also see
https://wiki.eclipse.org/Orion/How_Tos/Code_Edit

Could an html editor insert jQuery elements?

I've been playing with making an html editor with javascript functions:
So I have a very basic editor with a "bold" button which with I can make whatever text is selected bold, this is fine (I also have a number of other buttons too, but for simplicity and shortness of code I've missed them all out)
<head>
<script>
var editorDoc;
function InitEditable () {
var editor = document.getElementById ("editor");
editorDoc = editor.contentWindow.document;
var editorBody = editorDoc.body;
if ('contentEditable' in editorBody) {
editorBody.contentEditable = true;
}
else {
if ('designMode' in editorDoc) {
editorDoc.designMode = "on";
}
}
}
function ToggleBold () {
editorDoc.execCommand ('bold', false, null);
}
</script>
</head>
<body onload="InitEditable ();">
<button type="button" onclick="ToggleBold ();">Bold</button>
<iframe contenteditable="true" id="editor"></iframe>
</body>
However, something I was really interested in being able to implement would be adding a button which could insert, say, an accordion when pressed
This would then have to add other bits of script (I imagine) to be able to run each accordion (if you had more than one)
Although I haven't had much of a go at doing this myself yet, I was hoping to get a little insight into whether or not it's possible before starting

Google Custom Search on submit

I would like to customize my search form. I am using Google Search Service and have it linked to my domain and so on.
I chose the two column layout in the Control Panel, but however, I want to do something onSubmit of the form.
So I tried to put an actionlistener in jQuery into the form, however does not work.
Then I thought google certainly provides something for that. And yes they do. It is called:
setOnSubmitCallback()
http://code.google.com/apis/websearch/docs/reference.html
Unfortunately I dont get it.
So far I have:
google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
function initialize()
{
var searchControl = new google.search.CustomSearchControl('017998360718714977594:j6sbtr-d6x8');
searchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
searchControl.draw('cse', options);
}
google.setOnLoadCallback(initialize);
So i have two divs:
#cse-search-form for the form and #cse for the results
#cse is in another div #searchResults, that is hidden and here it comes:
I want to open #searchResults in a dialog from jQuery UI.
$("#searchResults").dialog( { minWidth: 750, minHeight: 750 } );
Which will result into:
.setOnSubmitCallback(function() {
$("#searchResults").dialog( { minWidth: 750, minHeight: 750 } );
} );
So my problem now is, where and on what do I have to put the setOnSubmitCallback?
I cannot put it on google.search.Search or CustomSearchControl as it is stated in the documentation. ANd I cannot call it in the onLoadCallback so it is very strange for me. Cannt figure out how to do that.
I hope somebody has some more experience for the google search and could help me out with a solution.
Thank you very much in advance.
NOTE: the code below is using something Google deprecated. Use this instead: http://code.google.com/apis/customsearch/v1/overview.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Hello World - Google Web Search API Sample</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
//<![CDATA[
google.load('search', '1');
google.load("jquery", "1.5.2");
google.load("jqueryui", "1.8.12");
function OnLoad() {
var searchComplete = function(searchControl, searcher){
$('#searchResults').dialog({modal: true, width: 700, height: 400, position: [50, 50]});
for (result in searcher.results) {
var content = searcher.results[result].content;
var title = searcher.results[result].title;
var url = searcher.results[result].url;
$('#searchResults ul')
.append($('<li></li>')
.append($('<a/>').attr('href', url).text(title))
.append($('<p/>').text(content)));
}
};
// called on form submit
newSearch = function(form) {
if (form.input.value) {
// Create a search control
var searchControl = new google.search.SearchControl();
// Add in a set of searchers
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.VideoSearch());
// tell the searchControl to draw itself (without this, the searchComplete won't get called - I'm not sure why)
searchControl.draw();
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setSearchCompleteCallback(this, searchComplete);
searchControl.execute(form.input.value);
}
return false;
}
// create a search form without a clear button
// bind form submission to my custom code
var container = document.getElementById("searchFormContainer");
this.searchForm = new google.search.SearchForm(false, container);
this.searchForm.setOnSubmitCallback(this, newSearch);
}
google.setOnLoadCallback(OnLoad);
//]]>
</script>
</head>
<body>
<div id="searchFormContainer">Loading</div>
<div id="searchResults" title="Search Results">
<ul></ul>
</div>
</body>
</html>

Categories

Resources