tinyMCE word counter for on paste help needed - tinymce

Good morning people, hope y'all are having a good time, first and foremost i want to thank y'all for your speedy response to my questions, a while ago i need a word counter for tinymce and i got some good response, this time i want when a user cut and paste into the counter it should also count the words and restrict them accordingly, here is the code to the onkey press counter
tinyMCE.init({
mode : "textareas",
elements : "teaser,headline",
setup: function(ed) {
var text = '';
var span = document.getElementById('word-count');
if(span)
{
var wordlimit = span.innerHTML;
ed.onKeyDown.add(function(ed, e) {
text = ed.getContent().replace(/(< ([^>]+)<)/g, '').replace(/\s+/g, ' ');
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
wordcount = wordlimit - (text.split(' ').length);
span.innerHTML = wordcount;
if(wordcount <= 0 && e.keyCode != 8)
{
return tinymce.dom.Event.cancel(e);
}
});
}
}
})
please can you help modify it for me to also watch for on paste. Thank you.
#cyberomin.

That is pretty forward:
ed.onPaste.add(function(ed, e) {
text = ed.getContent().replace(/(< ([^>]+)<)/g, '').replace(/\s+/g, ' ');
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
wordcount = wordlimit - (text.split(' ').length);
span.innerHTML = wordcount;
if(wordcount <= 0 && e.keyCode != 8)
{
return tinymce.dom.Event.cancel(e);
}
});

Related

Getting the cell given the cell value in google sheets using app script

I'm trying to write a script that tracks payment dates in google sheets (shows a different colour (either FontColor or Background) three days before payment, another colour on the day of payment and a totally different colour after the payment date.I'd appreciate if there's anyone with know how on how to use those values to get the cell name and use it to change the FontColor or alternatively if there's a better solution
Here is my google sheet
[![enter image description here][1]][1]
This is the code I've written to get the dates into a list
function myFunction() {
let spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
let lastRow = spreadsheet.getLastRow();
let lastCol = spreadsheet.getLastColumn();
var dataRange = spreadsheet.getActiveSheet().getRange(2, 11, lastRow, lastCol)
dataRange.setFontColor("green")
var data = dataRange.getDisplayValues();
let dates=[];
for (let i=0; i < dates.length; i++ ) {
// console.log(dates[i])
if (dates[i] === new Date().toLocaleDateString()) {
dataRange.setBackground('pink')
} else if (dates[i]) {
// do sth
} else {
// maintain the current state
}
}
}
Does it need to be with scripts?? With conditional formatting that would be MUCH faster, easier and uploads constantly.
You can apply it to the entire sheet or to a specific range. Use this custom formula (change A1 with the top left formula of your range)
=if(A1="",FALSE,(A1 - Today()) < 0)
Get sure to set these conditions in the correct order (in these case it would be preferrable to be the past dates, the actual date and the close future dates). Like this:
Here you have a link to play with:
https://docs.google.com/spreadsheets/d/1zhEFRQwOyAYQwXfv5lYTjI7B-6fIfz1rgdCt3MGvzmI/edit?usp=sharing
Payment Tracker
function paymentTracker() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const rg = sh.getRange(2, 11, sh.getLastRow() - 1, sh.getLastColumn() - 10);
rg.setFontColor("black")
const vs = rg.getDisplayValues();
const d = new Date();
//Logger.log('y: %s,m: %s,d: %s', d.getFullYear(), d.getMonth(), d.getDate());
const dt = new Date(d.getFullYear(), d.getMonth(), d.getDate());
const dtv = dt.valueOf();
const dt3 = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 3);
const dt3v = dt3.valueOf();
vs.forEach((r, i) => {
let ds = r.map(ds => {
let t = ds.split('/');
//Logger.log(JSON.stringify(t))
let v = new Date(Number(t[2]), Number(t[1]) - 1, Number(t[0])).valueOf();
let diff3 = dt3v - v;
if (dt3v == v) {
return "purple";
} else if (dtv == v) {
return "green";
} else {
return "pink";
}
});
sh.getRange(i + 2, 11, 1, ds.length).setBackgrounds([ds]);
})
}

How to create customized Add Comment in Word-Addins Taskpane?

I am creating an MS-Word Add-ins for Word for mac and I have to create a custom comment section with a task pane so I have created one textbox and create a button on click on button comment is added to that selected text.
I find many articles but don't work for me so that I attach a sample code below.
HTML File
<div class="padding">
<textarea id="areaDiv"></textarea>
<button id="addComment">Add Comment</button>
<div id="errorDiv"></div>
</div>
**JS File**
Office.onReady(function () {
// Office is ready
$(document).ready(function () {
// The document is ready
// Use this to check whether the API is supported in the Word client.
if (Office.context.requirements.isSetSupported('WordApi', '1.1')) {
// Do something that is only available via the new APIs
$('#addComment').click(addComment);
$('#supportedVersion').html('This code is using Word 2016 or later.');
}
else {
// Just letting you know that this code will not work with your version of Word.
$('#supportedVersion').html('This code requires Word 2016 or later.');
}
});
});
// Function that writes to a div with id='message' on the page.
function addComment() {
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
{ valueFormat: "unformatted", filterType: "all" },
function (asyncResult) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
write('');
}
else {
var range = asyncResult.value;
write(range);
}
});
}
function onError(error) {
$('#errorDiv').text(error.name + ' ' + error.code + ': ' + error.message);
}
function write(range) {
$('#errorDiv').text(range);
var text = $("#areaDiv").val();
if (range != null && range != "" && text != null && text != "") {
$('#errorDiv').text(range + " " + text);
var document = Office.context.document.properties.comments;
document.add(range, text);
$("#areaDiv").val("");
}
}
Here there is no error but there is an issue of no comment is set the selected text and not goes in the catch block.
If anyone has an idea about this then it helps me a lot.

How to add html in autocomplete ace editor?

Somebody can help me how to custom autocomplete for ace editor?
I need to display the emoji images such as below:
This editor is work well for me, but i need to insert the emoji images to the result of autocomplete.
var editor = ace.edit('editor');
editor.setTheme('ace/theme/github');
editor.getSession().setMode('ace/mode/markdown');
editor.$blockScrolling = Infinity; //prevents ace from logging annoying warnings
editor.getSession().on('change', function () {
draceditor.val(editor.getSession().getValue());
});
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true
});
// Ace autocomplete
var emojiWordCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
var wordList = emojis; // list emojis from `atwho/emojis.min.js`
var obj = editor.getSession().getTokenAt(pos.row, pos.column.count);
var curTokens = obj.value.split(/\s+/);
var lastToken = curTokens[curTokens.length-1];
if (lastToken[0] == ':') {
console.log(lastToken);
callback(null, wordList.map(function(word) {
return {
caption: word,
value: word.replace(':', '') + ' ',
meta: 'emoji' // this should return as text only.
};
}));
}
}
}
editor.completers = [emojiWordCompleter]
my bad idea, i try with this meta: '<img src="/path/to/emoji.png">', but of course it can't be work.
Any idea how to solve this? Thank so much before..
There is no built in way to do this.
You can create a custom renderer similar to https://github.com/c9/c9.ide.language.core/blob/bfb5dd2acc/completedp.js#L44, or modify https://github.com/ajaxorg/ace/blob/master/lib/ace/autocomplete/popup.js and create pull request to ace.

TinyMCE: wordcount plugin is not counting special characters as word

I have added the plugin wordcount to count the number of words entered in my TinyMCE texteditor.
plugins: "wordcount",
wordcount_cleanregex: /[.(),;:!?%#$?\x27\x22_+=\\/\-]*/g
It is counting letters and numbers but when I am giving a special character , it is not counting them.
for e.g ----
Hi I am 18 year old (for this it is giving me count 6)
Hi I am ## year old (for this it is giving me count 5)
Any idea what I need to do. I tried to remove:
%#$ from wordcount_cleanregex , but it didn't work.
Your issue is not with the wordcount_cleanregex setting but rather with the wordcount_countregex setting:
https://www.tinymce.com/docs/plugins/wordcount/#wordcount_countregex
If you look at the default one you will see why its skipping the characters that it is. Here is the exact regex:
https://regex101.com/r/wL4fL1/1
If you tweak that regex you can get it to count your ## as a word.
Note: There is some core cleaning that is done within the wordcount plugin that is done regardless of your configuration settings. In TinyMCE 4.4.1 it looks like this:
if (tx) {
tx = tx.replace(/\.\.\./g, ' '); // convert ellipses to spaces
tx = tx.replace(/<.[^<>]*?>/g, ' ').replace(/ | /gi, ' '); // remove html tags and space chars
// deal with html entities
tx = tx.replace(/(\w+)(&#?[a-z0-9]+;)+(\w+)/i, "$1$3").replace(/&.+?;/g, ' ');
tx = tx.replace(cleanre, ''); // remove numbers and punctuation
var wordArray = tx.match(countre);
if (wordArray) {
tc = wordArray.length;
}
}
...so some core things are still stripped from your content regardless of what you put in the wordcount_cleanregex and wordcount_countregex. If you want to change this core behavior you will need to modify the plugin's source code.
here is my wordcount plugin which I am adding externally , The function getCount returns the number of words perfectly when I run this function seprately on my .aspx page as javascript function, but when I am running under this plugin it is only counting letters (it is not counting any number/special characters)
tinymce.PluginManager.add('wordcount', function(editor) {
function update() {
editor.theme.panel.find('#wordcount').text(['Words: {0}', getCount()]);
}
editor.on('init', function() {
var statusbar = editor.theme.panel && editor.theme.panel.find('#statusbar')[0];
if (statusbar) {
tinymce.util.Delay.setEditorTimeout(editor, function() {
statusbar.insert({
type: 'label',
name: 'wordcount',
text: ['Words: {0}', getCount()],
classes: 'wordcount',
disabled: editor.settings.readonly
}, 0);
editor.on('setcontent beforeaddundo', update);
editor.on('keyup', function(e) {
if (e.keyCode == 32) {
update();
}
});
}, 0);
}
});
getCount = function () {
var body = editor.getBody().innerHTML;
text1 = body.replace(/<[^>]+>/g, '');
s = text1.replace(/ /g, ' ');
s = s.replace(/(^\s*)|(\s*$)/gi, "");//exclude start and end white-space
s = s.replace(/[ ]{2,}/gi, " ");//2 or more space to 1
s = s.replace(/\n /, "\n"); // exclude newline with a start spacing
return s.split(' ').length;
};
});

tinyMCE disable Undo/Redo function

I need to disable Undo/Redo function in tinyMCE. I saw the documentantion and I used this functions:
ed.onUndo.add(function(ed, e) {
tinymce.dom.Event.cancel(e);
e.preventDefault();
return false;
});
ed.onRedo.add(function(ed, e) {
tinymce.dom.Event.cancel(e);
e.preventDefault();
return false;
});
but without any success.
Note: ed is my active editor.
If you are using tinyMCE 4.*, you can disable Undo/Redo by returning false on BeforeAddUndo event:
ed.on('BeforeAddUndo', function(e) {
return false;
});
TinyMCE v4 - Just overwrite the default settings.
tinymce.init({
selector: '#content',
toolbar: 'bold italic strikethrough underline | quicklink | alignleft aligncenter alignright alignjustify | link ',
});
We had the same problem, but the solution is a bit hacky.
There is ajavascript class in the tinymce core that we needed to overwrite: tinymce.UndoManager.
We used a variable sticked to the editor object to decide if the creation of an undo step actually should take place or not: tinymce.activeEditor.disable_undo_creation.
Here is the code part of the overwritten class:
add : function(level) {
if (tinymce.activeEditor.disable_undo_creation) return;
var i, settings = editor.settings, lastLevel;
level = level || {};
level.content = getContent();
// Add undo level if needed
lastLevel = data[index];
if (lastLevel && lastLevel.content == level.content)
return null;
// Time to compress
if (settings.custom_undo_redo_levels) {
if (data.length > settings.custom_undo_redo_levels) {
for (i = 0; i < data.length - 1; i++)
data[i] = data[i + 1];
data.length--;
index = data.length;
}
}
// Get a non intrusive normalized bookmark
level.bookmark = editor.selection.getBookmark(2, true);
// Crop array if needed
if (index < data.length - 1)
data.length = index + 1;
data.push(level);
index = data.length - 1;
self.onAdd.dispatch(self, level);
editor.isNotDirty = 0;
return level;
},
When the editor is unable to create undo steps redo/undo won't work anymore.