How to edit the textarea that uses CodeMirror plugins? - javascript

I have a formatted / beautified text in the textarea (formatted using CodeMirror). Now I am not able to edit the textarea.
EDIT:
Here is the html portion Iam using
<div class="form-group ">
<textarea id="alertTemplate" class="form-control" placeholder="Condition " rows="5" id="comment"></textarea>
</div>
Here is the code I am using to convert the textarea content above to formatted javascript using codemirror
var editor;
var test = js_beautify(data.condition.script);
$('#alertTemplate').empty();
$('#alertTemplate').val(test);
editor = CodeMirror.fromTextArea(document.getElementById("alertTemplate"),{
lineNumbers: true,
theme: "default",
mode: "javascript",
readOnly: false
});

Make sure you have no readOnly: true in your setting.
window.onload = function () {
var readOnlyCodeMirror = CodeMirror.fromTextArea(document.getElementById('codesnippet_readonly'), {
mode: "javascript",
theme: "default",
lineNumbers: true,
readOnly: true
});
var editableCodeMirror = CodeMirror.fromTextArea(document.getElementById('codesnippet_editable'), {
mode: "javascript",
theme: "default",
lineNumbers: true
});
};
<h1>Using CodeMirror (readonly and editable code)</h1>
<p>http://codemirror.net/mode/javascript/index.html</p>
<link rel="stylesheet" href="http://codemirror.net/lib/codemirror.css">
<script src="http://codemirror.net/lib/codemirror.js"></script>
<script src="http://codemirror.net/addon/edit/matchbrackets.js"></script>
<script src="http://codemirror.net/addon/edit/continuecomment.js"></script>
<script src="http://codemirror.net/mode/javascript/javascript.js"></script>
<h2>Readonly</h2>
<div>
<textarea rows="4" cols="50" id="codesnippet_readonly" name="codesnippet_readonly">
// Demo code (the actual new parser character stream implementation)
var readOnlyCodeMirror = CodeMirror.fromTextArea(document.getElementById('codesnippet_readonly'), {
mode: "javascript",
theme: "default",
lineNumbers: true,
readOnly: true // This make the textarea readonly
});
</textarea>
</div>
<div>
<h2>Editable</h2>
<textarea rows="4" cols="50" name="codesnippet_editable" id="codesnippet_editable">
// Demo code (the actual new parser character stream implementation)
var editableCodeMirror = CodeMirror.fromTextArea(document.getElementById('codesnippet_editable'), {
mode: "javascript",
theme: "default",
lineNumbers: true
});
</textarea>
</div>

Related

CodeMirror: foldAll or unfoldAll from button?

I'd like to have buttons around the codemirror textarea that allow a user to unfoldAll or foldAll with the click of a button. This will avoid them having to learn shortcuts. Is it possible?
Here's the definition for the editor (the extraKeys do function as expected):
var editor = CodeMirror.fromTextArea(document.getElementById("xmlViewer"), {
mode: "text/html",
lineNumbers: true,
tabMode: 'indent',
lineWrapping: true,
autoCloseTags: true,
height: "650px",
width: "90%",
parserfile: "parsexml.js",
stylesheet: "css/xmlcolors.css",
path: "js/",
continuousScanning: 500,
extraKeys: {
"Ctrl-Q": function (cm) { cm.foldCode(cm.getCursor()); },
"Alt-F": "findPersistent",
"Ctrl-Y": "foldAll",
"Ctrl-I": "unfoldAll"
},
foldGutter: true,
autoRefresh: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
});
Here's the definition for the button:
<input type="button" id="expandAllBtn" value="Expand All" class="btn btn-outline-primary btn-sm" />
Here's the definition for the onclick:
$("#collapseAllBtn").on("click", function (e) {
editor.foldAll; // nothing happens
//editor.foldAll(); // error not a function
//editor.commands.foldAll(); // cannot read property of undefined
//editor.commands.foldAll; // cannot read property of undefined
});
The following is the way to accomplish this :
$("#collapseAllBtn").on("click", function (e) {
editor.execCommand("foldAll");
});

Vue Codemirror line numbers

So I am trying to implement codemirror into my Vue.js app using https://github.com/surmon-china/vue-codemirror. The problem is that after I import and use the codemirro component everything works fine expect the line numbers (number of lines the code has) are not showing. Here is my code right out of the demo page:
<template>
<div class="root">
<nav>
<div id="logo-container">
</div>
</nav>
<div id="left-side">
<div class="codemirror">
<!-- codemirror -->
<codemirror v-model="code"
:options="cmOption"
#cursorActivity="onCmCursorActivity"
#ready="onCmReady"
#focus="onCmFocus"
#blur="onCmBlur">
</codemirror>
</div>
</div>
</div>
</template>
and here is the script:
data() {
return {
code: '',
cmOption: {
tabSize: 4,
styleActiveLine: true,
lineNumbers: true,
styleSelectedText: true,
line: true,
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
mode: 'text/javascript',
// hint.js options
hintOptions:{
// 当匹配只有一项的时候是否自动补全
completeSingle: true
},
//快捷键 可提供三种模式 sublime、emacs、vim
keyMap: "sublime",
matchBrackets: true,
showCursorWhenSelecting: true,
theme: "monokai",
extraKeys: { "Ctrl": "autocomplete" }
}
}
}
In your codemirror configuration options there is string:
lineNumbers: false,
which turns off line numbers. Change it's value to true and it should solve the problem.

hint and fullscreen problems when codemirror is inside jquery layout

I am using codeMirror inside UI Layout Plug-in
Problems:
when inside layout, CodeMirror: Full Screen Editing does not work. F-11 to zoom, esc to quit
I tried full screen using jquery-fullscreen-plugin , seems to work fine but then autocomplete hint does not show up
with jquery-fullscreen-plugin , i tried giving hint container (see code below), works fine in full screen, does not work when not in full screen. Menu appear offset from cursor position.
I would prefer to use jquery-fullscreen-plugin but I dont know how to handle offset in hint menu because of container option
Complete Code (save as .html)
<!doctype html>
<title>CodeMirror: Any Word Completion Demo</title>
<meta charset="utf-8" />
<!-- codemirror-plugin -->
<link rel=stylesheet href="https://codemirror.net/doc/docs.css">
<link rel="stylesheet" href="https://codemirror.net/lib/codemirror.css">
<link rel="stylesheet" href="https://codemirror.net/addon/hint/show-hint.css">
<link rel="stylesheet" href="https://codemirror.net/addon/display/fullscreen.css">
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://codemirror.net/addon/hint/show-hint.js"></script>
<script src="https://codemirror.net/addon/hint/anyword-hint.js"></script>
<script src="https://codemirror.net/mode/shell/shell.js"></script>
<script src="https://codemirror.net/addon/display/fullscreen.js"></script>
<!-- layout.jquery-plugin -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<link type="text/css" rel="stylesheet" href="http://layout.jquery-dev.com/lib/css/layout-default-latest.css" />
<script type="text/javascript" src="http://layout.jquery-dev.com/lib/js/jquery-ui-latest.js"></script>
<script type="text/javascript" src="http://layout.jquery-dev.com/lib/js/jquery.layout-1.3.0.rc30.80.js"></script>
<!-- jquery-fullscreen-plugin -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-fullscreen-plugin/1.1.4/jquery.fullscreen-min.js"></script>
<!-- html -->
<div class="myDiv" style="height:800px">
<div class="ui-layout-center">Center</div>
<div class="ui-layout-north">North</div>
<div class="ui-layout-south">South</div>
<div class="ui-layout-east"> code Mirror
<div id="main-container">
<button id="fullscreenButton" type="button">Full-Screen</button>
<textarea id="code" name="code">
#!/bin/bash # clone the repository git clone http://github.com/garden/tree # generate HTTPS credentials cd tree openssl genrsa -aes256 -out https.key 1024 openssl req -new -nodes -key https.key -out https.csr openssl x509 -req -days 365 -in https.csr -signkey https.key -out https.crt cp https.key{,.orig} openssl rsa -in https.key.orig -out https.key # start the server in HTTPS mode cd web sudo node ../server.js 443 'yes' >> ../node.log & # here is how to stop the server for pid in `ps aux | grep 'node ../server.js' | awk '{print $2}'` ; do sudo kill -9 $pid 2> /dev/null done exit 0
</textarea>
</div>
</div>
<div class="ui-layout-west">West</div>
</div>
<!-- js -->
<script>
//
// setupCodeMirror
function setupCodeMirror() {
CodeMirror.commands.autocomplete = function(cm) {
cm.showHint({
hint: CodeMirror.hint.anyword,
container: $("#main-container").get(0)
});
};
//
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: 'shell',
theme: 'default',
lineWrapping: true,
lineNumbers: true,
extraKeys: {
"Ctrl-Space": "autocomplete",
"F11": function(cm) {
cm.setOption("fullScreen", !cm.getOption("fullScreen"));
},
"Esc": function(cm) {
if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
}
}
});
$("#fullscreenButton").click(function(event) {
$("#main-container").toggleFullScreen();
});
}
// init layout
$('.myDiv').layout({
resizeWhileDragging: true,
resizable: true,
east: {
size: 800
},
onload_end: function() {
setupCodeMirror();
}
});
//
</script>
</article>
As per my findings, built in cm.setOption("fullScreen", !cm.getOption("fullScreen")); will not work when inside jquery layout.
However with jquery-fullscreen-plugin , see the solution below.
Trick is set different showhint container before and after fullscreen event.
var showHintContainer = document.body;
// setupCodeMirror
function setupCodeMirror() {
CodeMirror.commands.autocomplete = function(cm) {
cm.showHint({
hint: CodeMirror.hint.anyword,
container: showHintContainer
});
};
//
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: 'shell',
theme: 'default',
lineWrapping: true,
lineNumbers: true,
extraKeys: {
"Ctrl-Space": "autocomplete"
}
});
$("#fullscreenButton").click(function(event) {
$("#main-container").toggleFullScreen();
});
$(document).bind("fullscreenchange", function() {
var fullScreenState = $(document).fullScreen() ? 'on' : 'off';
if (fullScreenState === 'on') {
showHintContainer = $("#main-container").get(0);
} else {
showHintContainer = document.body;
}
});
}
// init layout
$('.myDiv').layout({
resizeWhileDragging: true,
resizable: true,
east: {
size: 800
},
onload_end: function() {
setupCodeMirror();
}
});

How do I refresh the page after a DropdownList changes so that JavaScript will be executed

I know the title is confusing, so I'll evplaiin what i'm trying to do.
I am using the CodeMirror plugin to create a syntax-highlighted text area in MVC 5. I have a dropdownlist with a range of available languages that can be highlighted. I want to be able to swith the textarea language when the DDL changes. Right now, it is always stuck at the first language. Heres What I have So Far:
Model--->
public class CodeSnip
{
public string Title { get; set; }
public string Description { get; set; }
public StringBuilder Code { get; set; }
public LangType Language { get; set; }
}
public enum LangType
{
CSharp,
css,
HTML,
JavaScript,
Perl,
PHP,
Python,
Ruby,
SQL,
VB,
XML,
Other
}
The controller simply calls the appropriate view, no logic in there yet.
HTML/RAZOR--->
#using AFGCodeBox.Models
#model AFGCodeBox.Models.CodeSnip
<script src="/Scripts/CodeMirror/codemirror.js"></script>
<script src="/Scripts/CodeMirror/clike.js" type="text/javascript"></script>
<script src="~/Scripts/CodeMirror/css.js"></script>
<script src="~/Scripts/CodeMirror/htmlmixed.js"></script>
<script src="~/Scripts/CodeMirror/javascript.js"></script>
<script src="~/Scripts/CodeMirror/perl.js"></script>
<script src="~/Scripts/CodeMirror/php.js"></script>
<script src="~/Scripts/CodeMirror/python.js"></script>
<script src="~/Scripts/CodeMirror/ruby.js"></script>
<script src="~/Scripts/CodeMirror/sql.js"></script>
<script src="~/Scripts/CodeMirror/vb.js"></script>
<script src="~/Scripts/CodeMirror/xml.js"></script>
<link href="/Content/codemirror.css" rel="stylesheet" type="text/css" />
<link href="/Content/eclipse.css" rel="stylesheet" type="text/css"/>
<div class="jumbotron">
<h1>AFG Codebox</h1>
<p class="lead">Create your style here</p>
</div>
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
#Html.TextBoxFor(m => m.Title, new { type = "Search", autofocus = "true", id = "title", placeholder = "Codesnip Title", style = "width: 200px", #maxlength = "50" })
#Html.DropDownList("Language",
new SelectList(Enum.GetValues(typeof(LangType))),
"Select Language", new {id="codeDDl"})
<p></p>
#Html.TextAreaFor(m => m.Description, new { type = "Search", autofocus = "true", id = "description", placeholder = "Codesnip Description",style = "Width: 800px" })
<p></p>
<div id="CodeBlock">
#Html.TextAreaFor(m => m.Code, new { id = "code" })
</div>
}
<script>
switch(document.getElementById("codeDDl").selectedIndex) {
case 1:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csharp"
});
break;
case 2:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-css"
});
break;
case 3:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-html"
});
break;
case 4:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-javascript"
});
break;
}
</script>
You can see the DDL, codeDDL, which I want to fire the javascript case statement; but like I said it only calls index 0.
Is there a way to change the code boxes syntax by changing the selected index of the DDL?
You can do this like this :
#Html.DropDownList("Language",
new SelectList(Enum.GetValues(typeof(LangType))),
"Select Language",
new {id="codeDDl", #onchange="changeEditor()"})
function changeEditor(){
switch(document.getElementById("codeDDl").selectedIndex) {
case 1:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csharp"
});
break;
case 2:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-css"
});
break;
case 3:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-html"
});
break;
case 4:
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-javascript"
});
break;
}
}
You do not need to refresh the page, just bind an event handler to your drop down element and listen for event 'change' (which is fired when user select a value from drop down list), in the callback function add your code.
Below an example just to show the principal:
document.getElementById("codeDDl").addEventListener('change',function(e){
console.log('your code execute here!');
});
<select id="codeDDl">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

CodeMirror: XML code not being indented

I am using CodeMirror to display XML in XML mode, but the code is not being automatically indented.
I checked and the XML mode does implement indent(state, textAfter, fullLine), which handles the indenting, so it should be working.
This is how I am initializing CodeMirror:
CodeMirror.fromTextArea(document.getElementById("test"), {
mode: 'application/xml',
theme: 'eclipse',
lineNumbers: true,
lineWrapping: true,
readOnly: true,
cursorBlinkRate: -1
});
Check this jsFiddle link for a live version: https://jsfiddle.net/zrosfz7x.
Any ideas?
In order to provide a solution I have added an external beautifier for xml.
Here's a complete working example.
<html>
<head>
<meta charset="UTF-8">
<link rel=stylesheet href="//codemirror.net/lib/codemirror.css">
<script src=//codemirror.net/lib/codemirror.js></script>
<script src=//codemirror.net/mode/xml/xml.js></script>
<script src="//cdn.rawgit.com/vkiryukhin/vkBeautify/master/vkbeautify.js"></script>
</head>
<body>
<textarea id="test"><?xml version="1.0" encoding="UTF-8" ?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note></textarea>
<script>
document.getElementById("test").value = vkbeautify.xml(document.getElementById("test").value);
CodeMirror.fromTextArea(document.getElementById("test"), {
mode: 'application/xml',
// theme: 'eclipse',
lineNumbers: true,
lineWrapping: true,
readOnly: true,
cursorBlinkRate: -1
});
</script>
</body>
</html>
also here the updated jsFiddle: http://jsfiddle.net/zrosfz7x/3/

Categories

Resources