Reputation: 1383
I have a script that inserts formatted text into document. Is there any way to somehow isolate the formatting of inserted text, so that when user types afterwards the "normal" text does inherit the custom formatting?
here is the full code of the document script:
function onOpen (){
DocumentApp.getUi()
.createMenu("repro-formatting")
.addItem("Insert at cursor", "insert")
.addToUi();
}
function insert(){
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
if (!cursor) {
return;
}
var value = "###";
var text = cursor.insertText(value);
text.setBold(true);
text.setBackgroundColor("#f9cb9c");
var position = doc.newPosition(text, value.length);
doc.setCursor(position);
}
Upvotes: 0
Views: 100
Reputation: 201378
I believe your goal as follows.
When the formatted text is inserted, it seems that the cursor has the text format of the left side of the cursor. So, for example, it supposes that following situation.
12345
.1234
. In this case, 5
is the default text format.5
, when you insert new text from here, the text has the normal text format.4
, when you insert new text from here, the text has the custom formatted text.5
and when the backspace key is push (5
is deleted by the backspace key.), when you insert new text from here, the text has the normal text format.Although I tested several methods, unfortunately, I couldn't replicate the situation for pushing the backspace key using a script. Under above sample situation, when the cursor is put to the right of 5
and when 5
is deleted by a script, the text format couldn't be changed from the custom format.
When I saw your sample GIF animation, after you ran the script and the formatted text was added, it seems that you put a space and insert a text. If this situation can be used, I thought that a workaround might be able to be suggested.
In this answer, I would like to suggest the workaround. In this workaround, when the formatted text is inserted, a space, which has the text format before the custom format is inserted, is added. By this, when the new text is inserted after the script was run, the text with the text format before the script is run can be inserted.
When this workaround is reflected to your script, it becomes as follows.
function insert() {
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
if (!cursor) {
return;
}
var format = cursor.getElement().getAttributes();
var value = "###";
value += " ";
var text = cursor.insertText(value);
text.setBold(0, value.length - 1, true);
text.setBackgroundColor(0, value.length - 1, "#f9cb9c");
var position = doc.newPosition(text, value.length);
var t = doc.setCursor(position).getCursor().getElement().asText();
t.setAttributes(t.getText().length - 1, t.getText().length - 1, format);
}
###
is inserted, " "
which is a space is added.###
to the cursor and change the cursor position.
of ###
.
Upvotes: 2