]> git.lyx.org Git - features.git/blob - src/Text3.cpp
Centralize cancelation of export
[features.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "BranchList.h"
21 #include "Buffer.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "factory.h"
28 #include "FloatList.h"
29 #include "FuncStatus.h"
30 #include "FuncRequest.h"
31 #include "InsetList.h"
32 #include "Intl.h"
33 #include "Language.h"
34 #include "Layout.h"
35 #include "LyXAction.h"
36 #include "LyX.h"
37 #include "Lexer.h"
38 #include "LyXRC.h"
39 #include "Paragraph.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "TextClass.h"
43 #include "TextMetrics.h"
44 #include "Thesaurus.h"
45 #include "WordLangTuple.h"
46
47 #include "frontends/alert.h"
48 #include "frontends/Application.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include "insets/InsetArgument.h"
53 #include "insets/InsetCollapsible.h"
54 #include "insets/InsetCommand.h"
55 #include "insets/InsetExternal.h"
56 #include "insets/InsetFloat.h"
57 #include "insets/InsetFloatList.h"
58 #include "insets/InsetGraphics.h"
59 #include "insets/InsetGraphicsParams.h"
60 #include "insets/InsetInfo.h"
61 #include "insets/InsetIndexMacro.h"
62 #include "insets/InsetIPAMacro.h"
63 #include "insets/InsetNewline.h"
64 #include "insets/InsetQuotes.h"
65 #include "insets/InsetSpecialChar.h"
66 #include "insets/InsetText.h"
67 #include "insets/InsetWrap.h"
68
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/docstring_list.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lassert.h"
75 #include "support/limited_stack.h"
76 #include "support/lstrings.h"
77
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/InsetMathMacroTemplate.h"
80 #include "lyxfind.h"
81
82 #include <clocale>
83 #include <regex>
84 #include <sstream>
85
86 using namespace std;
87 using namespace lyx::support;
88
89 namespace lyx {
90
91 using cap::copySelection;
92 using cap::copySelectionToTemp;
93 using cap::cutSelection;
94 using cap::cutSelectionToTemp;
95 using cap::pasteFromStack;
96 using cap::pasteFromTemp;
97 using cap::pasteClipboardText;
98 using cap::pasteClipboardGraphics;
99 using cap::replaceSelection;
100 using cap::grabAndEraseSelection;
101 using cap::selClearOrDel;
102 using cap::pasteSimpleText;
103 using frontend::Clipboard;
104
105 // globals...
106 typedef limited_stack<pair<docstring, Font>> FontStack;
107 static FontStack freeFonts(15);
108 static bool toggleall = false;
109
110 static void toggleAndShow(Cursor & cur, Text * text,
111         Font const & font, bool togall = true)
112 {
113         text->toggleFree(cur, font, togall);
114
115         if (font.language() != ignore_language ||
116             font.fontInfo().number() != FONT_IGNORE) {
117                 TextMetrics const & tm = cur.bv().textMetrics(text);
118                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
119                                                        cur.real_current_font))
120                         text->setCursor(cur, cur.pit(), cur.pos(),
121                                         false, !cur.boundary());
122                 if (font.language() != ignore_language)
123                         // We need a buffer update if we change the language
124                         // (e.g., with info insets or if the selection contains
125                         // a par label)
126                         cur.forceBufferUpdate();
127         }
128 }
129
130
131 static void moveCursor(Cursor & cur, bool selecting)
132 {
133         if (selecting || cur.mark())
134                 cur.setSelection();
135 }
136
137
138 static void finishChange(Cursor & cur, bool selecting)
139 {
140         cur.finishUndo();
141         moveCursor(cur, selecting);
142 }
143
144
145 static void mathDispatch(Cursor & cur, FuncRequest const & cmd)
146 {
147         cur.recordUndo();
148         docstring sel = cur.selectionAsString(false);
149
150         // It may happen that sel is empty but there is a selection
151         replaceSelection(cur);
152
153         // Is this a valid formula?
154         bool valid = true;
155
156         if (sel.empty()) {
157 #ifdef ENABLE_ASSERTIONS
158                 const int old_pos = cur.pos();
159 #endif
160                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
161 #ifdef ENABLE_ASSERTIONS
162                 LATTEST(old_pos == cur.pos());
163 #endif
164                 cur.nextInset()->edit(cur, true);
165                 if (cmd.action() != LFUN_MATH_MODE)
166                         // LFUN_MATH_MODE has a different meaning in math mode
167                         cur.dispatch(cmd);
168         } else {
169                 InsetMathHull * formula = new InsetMathHull(cur.buffer());
170                 string const selstr = to_utf8(sel);
171                 istringstream is(selstr);
172                 Lexer lex;
173                 lex.setStream(is);
174                 if (!formula->readQuiet(lex)) {
175                         // No valid formula, let's try with delims
176                         is.str("$" + selstr + "$");
177                         lex.setStream(is);
178                         if (!formula->readQuiet(lex)) {
179                                 // Still not valid, leave it as is
180                                 valid = false;
181                                 delete formula;
182                                 cur.insert(sel);
183                         }
184                 }
185                 if (valid) {
186                         cur.insert(formula);
187                         cur.nextInset()->edit(cur, true);
188                         LASSERT(cur.inMathed(), return);
189                         cur.pos() = 0;
190                         cur.resetAnchor();
191                         cur.selection(true);
192                         cur.pos() = cur.lastpos();
193                         if (cmd.action() != LFUN_MATH_MODE)
194                                 // LFUN_MATH_MODE has a different meaning in math mode
195                                 cur.dispatch(cmd);
196                         cur.clearSelection();
197                         cur.pos() = cur.lastpos();
198                 }
199         }
200         if (valid)
201                 cur.message(from_utf8(N_("Math editor mode")));
202         else
203                 cur.message(from_utf8(N_("No valid math formula")));
204 }
205
206
207 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
208 {
209         LASSERT(cmd.action() == LFUN_REGEXP_MODE, return);
210         if (cur.inRegexped()) {
211                 cur.message(_("Already in regular expression mode"));
212                 return;
213         }
214         cur.recordUndo();
215         docstring sel = cur.selectionAsString(false);
216
217         // It may happen that sel is empty but there is a selection
218         replaceSelection(cur);
219
220         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
221         cur.nextInset()->edit(cur, true);
222         cur.niceInsert(sel);
223
224         cur.message(_("Regexp editor mode"));
225 }
226
227
228 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
229 {
230         cur.recordUndo();
231         cap::replaceSelection(cur);
232         cur.insert(new InsetSpecialChar(kind));
233         cur.posForward();
234 }
235
236
237 static void ipaChar(Cursor & cur, InsetIPAChar::Kind kind)
238 {
239         cur.recordUndo();
240         cap::replaceSelection(cur);
241         cur.insert(new InsetIPAChar(kind));
242         cur.posForward();
243 }
244
245
246 static bool doInsertInset(Cursor & cur, Text * text,
247                           FuncRequest const & cmd, bool edit,
248                           bool pastesel, bool resetfont = false)
249 {
250         Buffer & buffer = cur.bv().buffer();
251         BufferParams const & bparams = buffer.params();
252         Inset * inset = createInset(&buffer, cmd);
253         if (!inset)
254                 return false;
255
256         if (InsetCollapsible * ci = inset->asInsetCollapsible())
257                 ci->setButtonLabel();
258
259         cur.recordUndo();
260         if (cmd.action() == LFUN_ARGUMENT_INSERT) {
261                 bool cotextinsert = false;
262                 InsetArgument * const ia = static_cast<InsetArgument *>(inset);
263                 Layout const & lay = cur.paragraph().layout();
264                 Layout::LaTeXArgMap args = lay.args();
265                 Layout::LaTeXArgMap::const_iterator const lait = args.find(ia->name());
266                 if (lait != args.end())
267                         cotextinsert = (*lait).second.insertcotext;
268                 else {
269                         InsetLayout const & il = cur.inset().getLayout();
270                         args = il.args();
271                         Layout::LaTeXArgMap::const_iterator const ilait = args.find(ia->name());
272                         if (ilait != args.end())
273                                 cotextinsert = (*ilait).second.insertcotext;
274                 }
275                 // The argument requests to insert a copy of the co-text to the inset
276                 if (cotextinsert) {
277                         docstring ds;
278                         // If we have a selection within a paragraph, use this
279                         if (cur.selection() && cur.selBegin().pit() == cur.selEnd().pit())
280                                 ds = cur.selectionAsString(false);
281                         // else use the whole paragraph
282                         else
283                                 ds = cur.paragraph().asString();
284                         text->insertInset(cur, inset);
285                         ia->init(cur.paragraph());
286                         if (edit)
287                                 inset->edit(cur, true);
288                         // Now put co-text into inset
289                         Font const f(inherit_font, cur.current_font.language());
290                         if (!ds.empty()) {
291                                 cur.text()->insertStringAsLines(cur, ds, f);
292                                 cur.leaveInset(*inset);
293                         }
294                         return true;
295                 }
296         }
297
298         bool gotsel = false;
299         bool move_layout = false;
300         if (cur.selection()) {
301                 if (cmd.action() == LFUN_INDEX_INSERT)
302                         copySelectionToTemp(cur);
303                 else {
304                         cutSelectionToTemp(cur, pastesel);
305                         /* Move layout information inside the inset if the whole
306                          * paragraph and the inset allows setting layout
307                          * FIXME: this does not work as expected when change tracking is on
308                          *   However, we do not really know what to do in this case.
309                          * FIXME: figure out a good test in the environment case (see #12251).
310                          */
311                         if (cur.paragraph().layout().isCommand()
312                              && cur.paragraph().empty()
313                              && !inset->forcePlainLayout()) {
314                                 cur.paragraph().setPlainOrDefaultLayout(bparams.documentClass());
315                                 move_layout = true;
316                         }
317                 }
318                 cur.clearSelection();
319                 gotsel = true;
320         } else if (cmd.action() == LFUN_INDEX_INSERT) {
321                 gotsel = text->selectWordWhenUnderCursor(cur, WHOLE_WORD);
322                 copySelectionToTemp(cur);
323                 cur.clearSelection();
324         }
325         text->insertInset(cur, inset);
326
327         InsetText * inset_text = inset->asInsetText();
328         if (inset_text) {
329                 Font const & font = inset->inheritFont()
330                         ? cur.bv().textMetrics(text).displayFont(cur.pit(), cur.pos())
331                         : bparams.getFont();
332                 inset_text->setOuterFont(cur.bv(), font.fontInfo());
333         }
334
335         if (cmd.action() == LFUN_ARGUMENT_INSERT) {
336                 InsetArgument * const ia = static_cast<InsetArgument *>(inset);
337                 ia->init(cur.paragraph());
338         }
339
340         if (edit)
341                 inset->edit(cur, true);
342
343         if (!gotsel || !pastesel)
344                 return true;
345
346         pasteFromTemp(cur, cur.buffer()->errorList("Paste"));
347         cur.buffer()->errors("Paste");
348         cur.clearSelection(); // bug 393
349         cur.finishUndo();
350         if (inset_text) {
351                 if (resetfont) {
352                         // Reset of font (not language) is requested.
353                         // Used by InsetIndex (#11961).
354                         Language const * lang = cur.getFont().language();
355                         Font font(bparams.getFont().fontInfo(), lang);
356                         cur.paragraph().resetFonts(font);
357                 }
358                 inset_text->fixParagraphsFont();
359                 cur.pos() = 0;
360                 cur.pit() = 0;
361                 /* If the containing paragraph has kept its layout, reset the
362                  * layout of the first paragraph of the inset.
363                  */
364                 if (!move_layout)
365                         cur.paragraph().setPlainOrDefaultLayout(bparams.documentClass());
366                 // FIXME: what does this do?
367                 if (cmd.action() == LFUN_FLEX_INSERT)
368                         return true;
369                 Cursor old = cur;
370                 cur.leaveInset(*inset);
371                 if (cmd.action() == LFUN_PREVIEW_INSERT
372                         || cmd.action() == LFUN_IPA_INSERT)
373                         // trigger preview
374                         notifyCursorLeavesOrEnters(old, cur);
375         } else {
376                 cur.leaveInset(*inset);
377                 // reset surrounding par to default
378                 DocumentClass const & dc = bparams.documentClass();
379                 docstring const layoutname = inset->usePlainLayout()
380                         ? dc.plainLayoutName()
381                         : dc.defaultLayoutName();
382                 text->setLayout(cur, layoutname);
383         }
384         return true;
385 }
386
387
388 /// the type of outline operation
389 enum OutlineOp {
390         OutlineUp, // Move this header with text down
391         OutlineDown,   // Move this header with text up
392         OutlineIn, // Make this header deeper
393         OutlineOut // Make this header shallower
394 };
395
396
397 static void insertSeparator(Cursor const & cur, depth_type const depth)
398 {
399         Buffer & buf = *cur.buffer();
400         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
401         DocumentClass const & tc = buf.params().documentClass();
402         lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
403                                   + from_ascii("\" ignoreautonests")));
404         // FIXME: Bibitem mess!
405         if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
406                 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
407         lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
408         while (cur.paragraph().params().depth() > depth)
409                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
410 }
411
412
413 static void outline(OutlineOp mode, Cursor & cur, Text * text)
414 {
415         Buffer & buf = *cur.buffer();
416         pit_type & pit = cur.pit();
417         ParagraphList & pars = buf.text().paragraphs();
418         ParagraphList::iterator const bgn = pars.begin();
419         // The first paragraph of the area to be copied:
420         ParagraphList::iterator start = pars.iterator_at(pit);
421         // The final paragraph of area to be copied:
422         ParagraphList::iterator finish = start;
423         ParagraphList::iterator const end = pars.end();
424         depth_type const current_depth = cur.paragraph().params().depth();
425
426         int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
427         int toclevel;
428
429         // Move out (down) from this section header
430         if (finish != end)
431                 ++finish;
432
433         // Seek the one (on same level) below
434         for (; finish != end; ++finish) {
435                 toclevel = buf.text().getTocLevel(distance(bgn, finish));
436                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
437                         break;
438         }
439
440         switch (mode) {
441                 case OutlineUp: {
442                         if (start == pars.begin())
443                                 // Nothing to move.
444                                 return;
445                         ParagraphList::iterator dest = start;
446                         // Move out (up) from this header
447                         if (dest == bgn)
448                                 return;
449                         // Search previous same-level header above
450                         do {
451                                 --dest;
452                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
453                         } while(dest != bgn
454                                 && (toclevel == Layout::NOT_IN_TOC
455                                     || toclevel > thistoclevel));
456                         // Not found; do nothing
457                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
458                                 return;
459                         pit_type newpit = distance(bgn, dest);
460                         pit_type const len = distance(start, finish);
461                         pit_type const deletepit = pit + len;
462                         buf.undo().recordUndo(cur, newpit, deletepit - 1);
463                         // If we move an environment upwards, make sure it is
464                         // separated from its new neighbour below:
465                         // If an environment of the same layout follows, and the moved
466                         // paragraph sequence does not end with a separator, insert one.
467                         ParagraphList::iterator lastmoved = finish;
468                         --lastmoved;
469                         if (start->layout().isEnvironment()
470                             && dest->layout() == start->layout()
471                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
472                                 cur.pit() = distance(bgn, lastmoved);
473                                 cur.pos() = cur.lastpos();
474                                 insertSeparator(cur, current_depth);
475                                 cur.pit() = pit;
476                         }
477                         // Likewise, if we moved an environment upwards, make sure it
478                         // is separated from its new neighbour above.
479                         // The paragraph before the target of movement
480                         if (dest != bgn) {
481                                 ParagraphList::iterator before = dest;
482                                 --before;
483                                 // Get the parent paragraph (outer in nested context)
484                                 pit_type const parent =
485                                         before->params().depth() > current_depth
486                                                 ? text->depthHook(distance(bgn, before), current_depth)
487                                                 : distance(bgn, before);
488                                 // If a environment with same layout preceeds the moved one in the new
489                                 // position, and there is no separator yet, insert one.
490                                 if (start->layout().isEnvironment()
491                                     && pars[parent].layout() == start->layout()
492                                     && !before->isEnvSeparator(before->beginOfBody())) {
493                                         cur.pit() = distance(bgn, before);
494                                         cur.pos() = cur.lastpos();
495                                         insertSeparator(cur, current_depth);
496                                         cur.pit() = pit;
497                                 }
498                         }
499                         newpit = distance(bgn, dest);
500                         pars.splice(dest, start, finish);
501                         cur.pit() = newpit;
502                         break;
503                 }
504                 case OutlineDown: {
505                         if (finish == end)
506                                 // Nothing to move.
507                                 return;
508                         // Go one down from *this* header:
509                         ParagraphList::iterator dest = next(finish, 1);
510                         // Go further down to find header to insert in front of:
511                         for (; dest != end; ++dest) {
512                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
513                                 if (toclevel != Layout::NOT_IN_TOC
514                                       && toclevel <= thistoclevel)
515                                         break;
516                         }
517                         // One such was found, so go on...
518                         // If we move an environment downwards, make sure it is
519                         // separated from its new neighbour above.
520                         pit_type newpit = distance(bgn, dest);
521                         buf.undo().recordUndo(cur, pit, newpit - 1);
522                         // The paragraph before the target of movement
523                         ParagraphList::iterator before = dest;
524                         --before;
525                         // Get the parent paragraph (outer in nested context)
526                         pit_type const parent =
527                                 before->params().depth() > current_depth
528                                         ? text->depthHook(distance(bgn, before), current_depth)
529                                         : distance(bgn, before);
530                         // If a environment with same layout preceeds the moved one in the new
531                         // position, and there is no separator yet, insert one.
532                         if (start->layout().isEnvironment()
533                             && pars[parent].layout() == start->layout()
534                             && !before->isEnvSeparator(before->beginOfBody())) {
535                                 cur.pit() = distance(bgn, before);
536                                 cur.pos() = cur.lastpos();
537                                 insertSeparator(cur, current_depth);
538                                 cur.pit() = pit;
539                         }
540                         // Likewise, make sure moved environments are separated
541                         // from their new neighbour below:
542                         // If an environment of the same layout follows, and the moved
543                         // paragraph sequence does not end with a separator, insert one.
544                         ParagraphList::iterator lastmoved = finish;
545                         --lastmoved;
546                         if (dest != end
547                             && start->layout().isEnvironment()
548                             && dest->layout() == start->layout()
549                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
550                                 cur.pit() = distance(bgn, lastmoved);
551                                 cur.pos() = cur.lastpos();
552                                 insertSeparator(cur, current_depth);
553                                 cur.pit() = pit;
554                         }
555                         newpit = distance(bgn, dest);
556                         pit_type const len = distance(start, finish);
557                         pars.splice(dest, start, finish);
558                         cur.pit() = newpit - len;
559                         break;
560                 }
561                 case OutlineIn:
562                 case OutlineOut: {
563                         pit_type const len = distance(start, finish);
564                         buf.undo().recordUndo(cur, pit, pit + len - 1);
565                         for (; start != finish; ++start) {
566                                 toclevel = buf.text().getTocLevel(distance(bgn, start));
567                                 if (toclevel == Layout::NOT_IN_TOC)
568                                         continue;
569
570                                 DocumentClass const & tc = buf.params().documentClass();
571                                 int const newtoclevel =
572                                         (mode == OutlineIn ? toclevel + 1 : toclevel - 1);
573                                 LabelType const oldlabeltype = start->layout().labeltype;
574
575                                 for (auto const & lay : tc) {
576                                         if (lay.toclevel ==  newtoclevel &&
577                                                  lay.labeltype == oldlabeltype) {
578                                                 start->setLayout(lay);
579                                                 break;
580                                         }
581                                 }
582                         }
583                         break;
584                 }
585         }
586 }
587
588
589 void Text::number(Cursor & cur)
590 {
591         FontInfo font = ignore_font;
592         font.setNumber(FONT_TOGGLE);
593         toggleAndShow(cur, this, Font(font, ignore_language));
594 }
595
596
597 bool Text::isRTL(pit_type const pit) const
598 {
599         Buffer const & buffer = owner_->buffer();
600         return pars_[pit].isRTL(buffer.params());
601 }
602
603
604 namespace {
605
606 Language const * getLanguage(Cursor const & cur, string const & lang)
607 {
608         return lang.empty() ? cur.getFont().language() : languages.getLanguage(lang);
609 }
610
611
612 docstring resolveLayout(docstring layout, DocIterator const & dit)
613 {
614         Paragraph const & par = dit.paragraph();
615         DocumentClass const & tclass = dit.buffer()->params().documentClass();
616
617         if (layout.empty())
618                 layout = tclass.defaultLayoutName();
619
620         if (dit.inset().forcePlainLayout(dit.idx()))
621                 // in this case only the empty layout is allowed
622                 layout = tclass.plainLayoutName();
623         else if (par.usePlainLayout()) {
624                 // in this case, default layout maps to empty layout
625                 if (layout == tclass.defaultLayoutName())
626                         layout = tclass.plainLayoutName();
627         } else {
628                 // otherwise, the empty layout maps to the default
629                 if (layout == tclass.plainLayoutName())
630                         layout = tclass.defaultLayoutName();
631         }
632
633         // If the entry is obsolete, use the new one instead.
634         if (tclass.hasLayout(layout)) {
635                 docstring const & obs = tclass[layout].obsoleted_by();
636                 if (!obs.empty())
637                         layout = obs;
638         }
639         if (!tclass.hasLayout(layout))
640                 layout.clear();
641         return layout;
642 }
643
644
645 bool isAlreadyLayout(docstring const & layout, CursorData const & cur)
646 {
647         ParagraphList const & pars = cur.text()->paragraphs();
648
649         pit_type pit = cur.selBegin().pit();
650         pit_type const epit = cur.selEnd().pit() + 1;
651         for ( ; pit != epit; ++pit)
652                 if (pars[pit].layout().name() != layout)
653                         return false;
654
655         return true;
656 }
657
658
659 } // namespace
660
661
662 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
663 {
664         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
665
666         // Dispatch if the cursor is inside the text. It is not the
667         // case for context menus (bug 5797).
668         if (cur.text() != this) {
669                 cur.undispatched();
670                 return;
671         }
672
673         BufferView * bv = &cur.bv();
674         TextMetrics * tm = &bv->textMetrics(this);
675         if (!tm->contains(cur.pit())) {
676                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
677                 tm = &bv->textMetrics(this);
678         }
679
680         // FIXME: We use the update flag to indicates wether a singlePar or a
681         // full screen update is needed. We reset it here but shall we restore it
682         // at the end?
683         cur.noScreenUpdate();
684
685         LBUFERR(this == cur.text());
686
687         // NOTE: This should NOT be a reference. See commit 94a5481a.
688         CursorSlice const oldTopSlice = cur.top();
689         bool const oldBoundary = cur.boundary();
690         bool const oldSelection = cur.selection();
691         // Signals that, even if needsUpdate == false, an update of the
692         // cursor paragraph is required
693         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action(),
694                 LyXAction::SingleParUpdate);
695         // Signals that a full-screen update is required
696         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action(),
697                 LyXAction::NoUpdate) || singleParUpdate);
698         bool const last_misspelled = lyxrc.spellcheck_continuously
699                 && cur.paragraph().isMisspelled(cur.pos(), true);
700
701         FuncCode const act = cmd.action();
702         switch (act) {
703
704         case LFUN_PARAGRAPH_MOVE_DOWN: {
705                 pit_type const pit = cur.pit();
706                 cur.recordUndo(pit, pit + 1);
707                 pars_.swap(pit, pit + 1);
708                 needsUpdate = true;
709                 cur.forceBufferUpdate();
710                 ++cur.pit();
711                 break;
712         }
713
714         case LFUN_PARAGRAPH_MOVE_UP: {
715                 pit_type const pit = cur.pit();
716                 cur.recordUndo(pit - 1, pit);
717                 cur.finishUndo();
718                 pars_.swap(pit, pit - 1);
719                 --cur.pit();
720                 needsUpdate = true;
721                 cur.forceBufferUpdate();
722                 break;
723         }
724
725         case LFUN_APPENDIX: {
726                 Paragraph & par = cur.paragraph();
727                 bool start = !par.params().startOfAppendix();
728
729 // FIXME: The code below only makes sense at top level.
730 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
731                 // ensure that we have only one start_of_appendix in this document
732                 // FIXME: this don't work for multipart document!
733                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
734                         if (pars_[tmp].params().startOfAppendix()) {
735                                 cur.recordUndo(tmp, tmp);
736                                 pars_[tmp].params().startOfAppendix(false);
737                                 break;
738                         }
739                 }
740
741                 cur.recordUndo();
742                 par.params().startOfAppendix(start);
743
744                 // we can set the refreshing parameters now
745                 cur.forceBufferUpdate();
746                 break;
747         }
748
749         case LFUN_WORD_DELETE_FORWARD:
750                 if (cur.selection())
751                         cutSelection(cur, false);
752                 else
753                         deleteWordForward(cur, cmd.getArg(0) == "force");
754                 finishChange(cur, false);
755                 break;
756
757         case LFUN_WORD_DELETE_BACKWARD:
758                 if (cur.selection())
759                         cutSelection(cur, false);
760                 else
761                         deleteWordBackward(cur, cmd.getArg(0) == "force");
762                 finishChange(cur, false);
763                 break;
764
765         case LFUN_LINE_DELETE_FORWARD:
766                 if (cur.selection())
767                         cutSelection(cur, false);
768                 else
769                         tm->deleteLineForward(cur);
770                 finishChange(cur, false);
771                 break;
772
773         case LFUN_BUFFER_BEGIN:
774         case LFUN_BUFFER_BEGIN_SELECT:
775                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_BEGIN_SELECT);
776                 if (cur.depth() == 1)
777                         needsUpdate |= cursorTop(cur);
778                 else
779                         cur.undispatched();
780                 cur.screenUpdateFlags(Update::FitCursor);
781                 break;
782
783         case LFUN_BUFFER_END:
784         case LFUN_BUFFER_END_SELECT:
785                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_END_SELECT);
786                 if (cur.depth() == 1)
787                         needsUpdate |= cursorBottom(cur);
788                 else
789                         cur.undispatched();
790                 cur.screenUpdateFlags(Update::FitCursor);
791                 break;
792
793         case LFUN_INSET_BEGIN:
794         case LFUN_INSET_BEGIN_SELECT:
795                 needsUpdate |= cur.selHandle(act == LFUN_INSET_BEGIN_SELECT);
796                 if (cur.depth() == 1 || !cur.top().at_begin())
797                         needsUpdate |= cursorTop(cur);
798                 else
799                         cur.undispatched();
800                 cur.screenUpdateFlags(Update::FitCursor);
801                 break;
802
803         case LFUN_INSET_END:
804         case LFUN_INSET_END_SELECT:
805                 needsUpdate |= cur.selHandle(act == LFUN_INSET_END_SELECT);
806                 if (cur.depth() == 1 || !cur.top().at_end())
807                         needsUpdate |= cursorBottom(cur);
808                 else
809                         cur.undispatched();
810                 cur.screenUpdateFlags(Update::FitCursor);
811                 break;
812
813         case LFUN_CHAR_FORWARD:
814         case LFUN_CHAR_FORWARD_SELECT: {
815                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
816                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_FORWARD_SELECT);
817                 bool const cur_moved = cursorForward(cur);
818                 needsUpdate |= cur_moved;
819
820                 if (!cur_moved && cur.depth() > 1
821                      && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
822                         cur.undispatched();
823                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
824
825                         // we will be moving out the inset, so we should execute
826                         // the depm-mechanism.
827                         // The cursor hasn't changed yet. To give the DEPM the
828                         // possibility of doing something we must provide it with
829                         // two different cursors.
830                         Cursor dummy = cur;
831                         dummy.pos() = dummy.pit() = 0;
832                         if (cur.bv().checkDepm(dummy, cur))
833                                 cur.forceBufferUpdate();
834                 }
835                 break;
836         }
837
838         case LFUN_CHAR_BACKWARD:
839         case LFUN_CHAR_BACKWARD_SELECT: {
840                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
841                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_BACKWARD_SELECT);
842                 bool const cur_moved = cursorBackward(cur);
843                 needsUpdate |= cur_moved;
844
845                 if (!cur_moved && cur.depth() > 1
846                      && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
847                         cur.undispatched();
848                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
849
850                         // we will be moving out the inset, so we should execute
851                         // the depm-mechanism.
852                         // The cursor hasn't changed yet. To give the DEPM the
853                         // possibility of doing something we must provide it with
854                         // two different cursors.
855                         Cursor dummy = cur;
856                         dummy.pos() = cur.lastpos();
857                         dummy.pit() = cur.lastpit();
858                         if (cur.bv().checkDepm(dummy, cur))
859                                 cur.forceBufferUpdate();
860                 }
861                 break;
862         }
863
864         case LFUN_CHAR_LEFT:
865         case LFUN_CHAR_LEFT_SELECT:
866                 if (lyxrc.visual_cursor) {
867                         needsUpdate |= cur.selHandle(act == LFUN_CHAR_LEFT_SELECT);
868                         bool const cur_moved = cursorVisLeft(cur);
869                         needsUpdate |= cur_moved;
870                         if (!cur_moved && cur.depth() > 1
871                              && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
872                                 cur.undispatched();
873                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
874                         }
875                 } else {
876                         if (cur.reverseDirectionNeeded()) {
877                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
878                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
879                         } else {
880                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
881                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
882                         }
883                         dispatch(cur, cmd);
884                         return;
885                 }
886                 break;
887
888         case LFUN_CHAR_RIGHT:
889         case LFUN_CHAR_RIGHT_SELECT:
890                 if (lyxrc.visual_cursor) {
891                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_CHAR_RIGHT_SELECT);
892                         bool const cur_moved = cursorVisRight(cur);
893                         needsUpdate |= cur_moved;
894                         if (!cur_moved && cur.depth() > 1
895                              && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
896                                 cur.undispatched();
897                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
898                         }
899                 } else {
900                         if (cur.reverseDirectionNeeded()) {
901                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
902                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
903                         } else {
904                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
905                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
906                         }
907                         dispatch(cur, cmd);
908                         return;
909                 }
910                 break;
911
912
913         case LFUN_UP_SELECT:
914         case LFUN_DOWN_SELECT:
915         case LFUN_UP:
916         case LFUN_DOWN: {
917                 // stop/start the selection
918                 bool select = cmd.action() == LFUN_DOWN_SELECT ||
919                         cmd.action() == LFUN_UP_SELECT;
920
921                 // move cursor up/down
922                 bool up = cmd.action() == LFUN_UP_SELECT || cmd.action() == LFUN_UP;
923                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
924
925                 if (!atFirstOrLastRow) {
926                         needsUpdate |= cur.selHandle(select);
927                         cur.upDownInText(up, needsUpdate);
928                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
929                 } else {
930                         pos_type newpos = up ? 0 : cur.lastpos();
931                         if (lyxrc.mac_like_cursor_movement && cur.pos() != newpos) {
932                                 needsUpdate |= cur.selHandle(select);
933                                 // we do not reset the targetx of the cursor
934                                 cur.pos() = newpos;
935                                 needsUpdate |= bv->checkDepm(cur, bv->cursor());
936                                 cur.updateTextTargetOffset();
937                                 if (needsUpdate)
938                                         cur.forceBufferUpdate();
939                                 break;
940                         }
941
942                         // if the cursor cannot be moved up or down do not remove
943                         // the selection right now, but wait for the next dispatch.
944                         if (select)
945                                 needsUpdate |= cur.selHandle(select);
946                         cur.upDownInText(up, needsUpdate);
947                         cur.undispatched();
948                 }
949
950                 break;
951         }
952
953         case LFUN_PARAGRAPH_SELECT:
954                 if (cur.pos() > 0)
955                         needsUpdate |= setCursor(cur, cur.pit(), 0);
956                 needsUpdate |= cur.selHandle(true);
957                 if (cur.pos() < cur.lastpos())
958                         needsUpdate |= setCursor(cur, cur.pit(), cur.lastpos());
959                 break;
960
961         case LFUN_PARAGRAPH_UP:
962         case LFUN_PARAGRAPH_UP_SELECT:
963                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_UP_SELECT);
964                 needsUpdate |= cursorUpParagraph(cur);
965                 break;
966
967         case LFUN_PARAGRAPH_DOWN:
968         case LFUN_PARAGRAPH_DOWN_SELECT:
969                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_DOWN_SELECT);
970                 needsUpdate |= cursorDownParagraph(cur);
971                 break;
972
973         case LFUN_LINE_BEGIN:
974         case LFUN_LINE_BEGIN_SELECT:
975                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_BEGIN_SELECT);
976                 needsUpdate |= tm->cursorHome(cur);
977                 break;
978
979         case LFUN_LINE_END:
980         case LFUN_LINE_END_SELECT:
981                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_END_SELECT);
982                 needsUpdate |= tm->cursorEnd(cur);
983                 break;
984
985         case LFUN_SECTION_SELECT: {
986                 Buffer const & buf = *cur.buffer();
987                 pit_type const pit = cur.pit();
988                 ParagraphList & pars = buf.text().paragraphs();
989                 ParagraphList::iterator bgn = pars.begin();
990                 // The first paragraph of the area to be selected:
991                 ParagraphList::iterator start = pars.iterator_at(pit);
992                 // The final paragraph of area to be selected:
993                 ParagraphList::iterator finish = start;
994                 ParagraphList::iterator end = pars.end();
995
996                 int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
997                 if (thistoclevel == Layout::NOT_IN_TOC)
998                         break;
999
1000                 cur.pos() = 0;
1001                 Cursor const old_cur = cur;
1002                 needsUpdate |= cur.selHandle(true);
1003
1004                 // Move out (down) from this section header
1005                 if (finish != end)
1006                         ++finish;
1007
1008                 // Seek the one (on same level) below
1009                 for (; finish != end; ++finish, ++cur.pit()) {
1010                         int const toclevel = buf.text().getTocLevel(distance(bgn, finish));
1011                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
1012                                 break;
1013                 }
1014                 cur.pos() = cur.lastpos();
1015                 cur.boundary(false);
1016                 cur.setCurrentFont();
1017
1018                 needsUpdate |= cur != old_cur;
1019                 break;
1020         }
1021
1022         case LFUN_WORD_RIGHT:
1023         case LFUN_WORD_RIGHT_SELECT:
1024                 if (lyxrc.visual_cursor) {
1025                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_RIGHT_SELECT);
1026                         bool const cur_moved = cursorVisRightOneWord(cur);
1027                         needsUpdate |= cur_moved;
1028                         if (!cur_moved && cur.depth() > 1
1029                              && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
1030                                 cur.undispatched();
1031                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1032                         }
1033                 } else {
1034                         if (cur.reverseDirectionNeeded()) {
1035                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
1036                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
1037                         } else {
1038                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
1039                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
1040                         }
1041                         dispatch(cur, cmd);
1042                         return;
1043                 }
1044                 break;
1045
1046         case LFUN_WORD_FORWARD:
1047         case LFUN_WORD_FORWARD_SELECT: {
1048                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_FORWARD_SELECT);
1049                 bool const cur_moved = cursorForwardOneWord(cur);
1050                 needsUpdate |= cur_moved;
1051
1052                 if (!cur_moved && cur.depth() > 1
1053                      && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
1054                         cur.undispatched();
1055                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1056
1057                         // we will be moving out the inset, so we should execute
1058                         // the depm-mechanism.
1059                         // The cursor hasn't changed yet. To give the DEPM the
1060                         // possibility of doing something we must provide it with
1061                         // two different cursors.
1062                         Cursor dummy = cur;
1063                         dummy.pos() = dummy.pit() = 0;
1064                         if (cur.bv().checkDepm(dummy, cur))
1065                                 cur.forceBufferUpdate();
1066                 }
1067                 break;
1068         }
1069
1070         case LFUN_WORD_LEFT:
1071         case LFUN_WORD_LEFT_SELECT:
1072                 if (lyxrc.visual_cursor) {
1073                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_LEFT_SELECT);
1074                         bool const cur_moved = cursorVisLeftOneWord(cur);
1075                         needsUpdate |= cur_moved;
1076                         if (!cur_moved && cur.depth() > 1
1077                              && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
1078                                 cur.undispatched();
1079                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
1080                         }
1081                 } else {
1082                         if (cur.reverseDirectionNeeded()) {
1083                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
1084                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
1085                         } else {
1086                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
1087                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
1088                         }
1089                         dispatch(cur, cmd);
1090                         return;
1091                 }
1092                 break;
1093
1094         case LFUN_WORD_BACKWARD:
1095         case LFUN_WORD_BACKWARD_SELECT: {
1096                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_BACKWARD_SELECT);
1097                 bool const cur_moved = cursorBackwardOneWord(cur);
1098                 needsUpdate |= cur_moved;
1099
1100                 if (!cur_moved && cur.depth() > 1
1101                      && oldTopSlice == cur.top() && cur.boundary() == oldBoundary) {
1102                         cur.undispatched();
1103                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1104
1105                         // we will be moving out the inset, so we should execute
1106                         // the depm-mechanism.
1107                         // The cursor hasn't changed yet. To give the DEPM the
1108                         // possibility of doing something we must provide it with
1109                         // two different cursors.
1110                         Cursor dummy = cur;
1111                         dummy.pos() = cur.lastpos();
1112                         dummy.pit() = cur.lastpit();
1113                         if (cur.bv().checkDepm(dummy, cur))
1114                                 cur.forceBufferUpdate();
1115                 }
1116                 break;
1117         }
1118
1119         case LFUN_WORD_SELECT: {
1120                 selectWord(cur, WHOLE_WORD);
1121                 finishChange(cur, true);
1122                 break;
1123         }
1124
1125         case LFUN_NEWLINE_INSERT: {
1126                 InsetNewlineParams inp;
1127                 docstring const & arg = cmd.argument();
1128                 if (arg == "linebreak")
1129                         inp.kind = InsetNewlineParams::LINEBREAK;
1130                 else
1131                         inp.kind = InsetNewlineParams::NEWLINE;
1132                 cap::replaceSelection(cur);
1133                 cur.recordUndo();
1134                 cur.insert(new InsetNewline(inp));
1135                 cur.posForward();
1136                 moveCursor(cur, false);
1137                 break;
1138         }
1139
1140         case LFUN_TAB_INSERT: {
1141                 bool const multi_par_selection = cur.selection() &&
1142                         cur.selBegin().pit() != cur.selEnd().pit();
1143                 if (multi_par_selection) {
1144                         // If there is a multi-paragraph selection, a tab is inserted
1145                         // at the beginning of each paragraph.
1146                         cur.recordUndoSelection();
1147                         pit_type const pit_end = cur.selEnd().pit();
1148                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
1149                                 pars_[pit].insertChar(0, '\t',
1150                                                       bv->buffer().params().track_changes);
1151                                 // Update the selection pos to make sure the selection does not
1152                                 // change as the inserted tab will increase the logical pos.
1153                                 if (cur.realAnchor().pit() == pit)
1154                                         cur.realAnchor().forwardPos();
1155                                 if (cur.pit() == pit)
1156                                         cur.forwardPos();
1157                         }
1158                         cur.finishUndo();
1159                 } else {
1160                         // Maybe we shouldn't allow tabs within a line, because they
1161                         // are not (yet) aligned as one might do expect.
1162                         FuncRequest ncmd(LFUN_SELF_INSERT, from_ascii("\t"));
1163                         dispatch(cur, ncmd);
1164                 }
1165                 break;
1166         }
1167
1168         case LFUN_TAB_DELETE: {
1169                 bool const tc = bv->buffer().params().track_changes;
1170                 if (cur.selection()) {
1171                         // If there is a selection, a tab (if present) is removed from
1172                         // the beginning of each paragraph.
1173                         cur.recordUndoSelection();
1174                         pit_type const pit_end = cur.selEnd().pit();
1175                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
1176                                 Paragraph & par = paragraphs()[pit];
1177                                 if (par.empty())
1178                                         continue;
1179                                 char_type const c = par.getChar(0);
1180                                 if (c == '\t' || c == ' ') {
1181                                         // remove either 1 tab or 4 spaces.
1182                                         int const n = (c == ' ' ? 4 : 1);
1183                                         for (int i = 0; i < n
1184                                                   && !par.empty() && par.getChar(0) == c; ++i) {
1185                                                 if (cur.pit() == pit)
1186                                                         cur.posBackward();
1187                                                 if (cur.realAnchor().pit() == pit
1188                                                           && cur.realAnchor().pos() > 0 )
1189                                                         cur.realAnchor().backwardPos();
1190                                                 par.eraseChar(0, tc);
1191                                         }
1192                                 }
1193                         }
1194                         cur.finishUndo();
1195                 } else {
1196                         // If there is no selection, try to remove a tab or some spaces
1197                         // before the position of the cursor.
1198                         Paragraph & par = paragraphs()[cur.pit()];
1199                         pos_type const pos = cur.pos();
1200
1201                         if (pos == 0)
1202                                 break;
1203
1204                         char_type const c = par.getChar(pos - 1);
1205                         cur.recordUndo();
1206                         if (c == '\t') {
1207                                 cur.posBackward();
1208                                 par.eraseChar(cur.pos(), tc);
1209                         } else
1210                                 for (int n_spaces = 0;
1211                                      cur.pos() > 0
1212                                              && par.getChar(cur.pos() - 1) == ' '
1213                                              && n_spaces < 4;
1214                                      ++n_spaces) {
1215                                         cur.posBackward();
1216                                         par.eraseChar(cur.pos(), tc);
1217                                 }
1218                         cur.finishUndo();
1219                 }
1220                 break;
1221         }
1222
1223         case LFUN_CHAR_DELETE_FORWARD:
1224                 if (!cur.selection()) {
1225                         if (cur.pos() == cur.paragraph().size())
1226                                 // Par boundary, force full-screen update
1227                                 singleParUpdate = false;
1228                         else if (cmd.getArg(0) != "force" && cur.confirmDeletion()) {
1229                                 cur.resetAnchor();
1230                                 cur.selection(true);
1231                                 cur.posForward();
1232                                 cur.setSelection();
1233                                 break;
1234                         }
1235                         needsUpdate |= erase(cur);
1236                         cur.resetAnchor();
1237                 } else {
1238                         cutSelection(cur, false);
1239                         cur.setCurrentFont();
1240                         singleParUpdate = false;
1241                 }
1242                 moveCursor(cur, false);
1243                 break;
1244
1245         case LFUN_CHAR_DELETE_BACKWARD:
1246                 if (!cur.selection()) {
1247                         if (bv->getIntl().getTransManager().backspace()) {
1248                                 bool par_boundary = cur.pos() == 0;
1249                                 bool first_par = cur.pit() == 0;
1250                                 // Par boundary, full-screen update
1251                                 if (par_boundary)
1252                                         singleParUpdate = false;
1253                                 else if (cmd.getArg(0) != "force" && cur.confirmDeletion(true)) {
1254                                         cur.resetAnchor();
1255                                         cur.selection(true);
1256                                         cur.posBackward();
1257                                         cur.setSelection();
1258                                         break;
1259                                 }
1260                                 needsUpdate |= backspace(cur);
1261                                 cur.resetAnchor();
1262                                 if (par_boundary && !first_par && cur.pos() > 0
1263                                     && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
1264                                         needsUpdate |= backspace(cur);
1265                                         cur.resetAnchor();
1266                                 }
1267                         }
1268                 } else {
1269                         DocIterator const dit = cur.selectionBegin();
1270                         cutSelection(cur, false);
1271                         if (cur.buffer()->params().track_changes)
1272                                 // since we're doing backwards deletion,
1273                                 // and the selection is not really cut,
1274                                 // move cursor before selection (#11630)
1275                                 cur.setCursor(dit);
1276                         cur.setCurrentFont();
1277                         singleParUpdate = false;
1278                 }
1279                 break;
1280
1281         case LFUN_PARAGRAPH_BREAK: {
1282                 cap::replaceSelection(cur);
1283                 pit_type pit = cur.pit();
1284                 Paragraph const & par = pars_[pit];
1285                 bool lastpar = (pit == pit_type(pars_.size() - 1));
1286                 Paragraph const & nextpar = lastpar ? par : pars_[pit + 1];
1287                 pit_type prev = pit > 0 ? depthHook(pit, par.getDepth()) : pit;
1288                 if (prev < pit && cur.pos() == par.beginOfBody()
1289                     && par.empty() && !par.isEnvSeparator(cur.pos())
1290                     && !par.layout().keepempty
1291                     && !par.layout().isCommand()
1292                     && pars_[prev].layout() != par.layout()
1293                     && pars_[prev].layout().isEnvironment()
1294                     && !nextpar.isEnvSeparator(nextpar.beginOfBody())) {
1295                         if (par.layout().isEnvironment()
1296                             && pars_[prev].getDepth() == par.getDepth()) {
1297                                 docstring const layout = par.layout().name();
1298                                 DocumentClass const & tc = bv->buffer().params().documentClass();
1299                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, tc.plainLayout().name()));
1300                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1301                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1302                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1303                         } else {
1304                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1305                                 breakParagraph(cur);
1306                         }
1307                         Font const f(inherit_font, cur.current_font.language());
1308                         pars_[cur.pit() - 1].resetFonts(f);
1309                 } else {
1310                         if (par.isEnvSeparator(cur.pos()) && cmd.getArg(1) != "ignoresep")
1311                                 cur.posForward();
1312                         breakParagraph(cur, cmd.getArg(0) == "inverse");
1313                 }
1314                 cur.resetAnchor();
1315                 // If we have a list and autoinsert item insets,
1316                 // insert them now.
1317                 Layout::LaTeXArgMap args = par.layout().args();
1318                 for (auto const & thearg : args) {
1319                         Layout::latexarg arg = thearg.second;
1320                         if (arg.autoinsert && prefixIs(thearg.first, "item:")) {
1321                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, thearg.first);
1322                                 lyx::dispatch(cmd2);
1323                         }
1324                 }
1325                 break;
1326         }
1327
1328         case LFUN_INSET_INSERT: {
1329                 cur.recordUndo();
1330
1331                 // We have to avoid triggering InstantPreview loading
1332                 // before inserting into the document. See bug #5626.
1333                 bool loaded = bv->buffer().isFullyLoaded();
1334                 bv->buffer().setFullyLoaded(false);
1335                 Inset * inset = createInset(&bv->buffer(), cmd);
1336                 bv->buffer().setFullyLoaded(loaded);
1337
1338                 if (inset) {
1339                         // FIXME (Abdel 01/02/2006):
1340                         // What follows would be a partial fix for bug 2154:
1341                         //   http://www.lyx.org/trac/ticket/2154
1342                         // This automatically put the label inset _after_ a
1343                         // numbered section. It should be possible to extend the mechanism
1344                         // to any kind of LateX environement.
1345                         // The correct way to fix that bug would be at LateX generation.
1346                         // I'll let the code here for reference as it could be used for some
1347                         // other feature like "automatic labelling".
1348                         /*
1349                         Paragraph & par = pars_[cur.pit()];
1350                         if (inset->lyxCode() == LABEL_CODE
1351                                 && !par.layout().counter.empty()) {
1352                                 // Go to the end of the paragraph
1353                                 // Warning: Because of Change-Tracking, the last
1354                                 // position is 'size()' and not 'size()-1':
1355                                 cur.pos() = par.size();
1356                                 // Insert a new paragraph
1357                                 FuncRequest fr(LFUN_PARAGRAPH_BREAK);
1358                                 dispatch(cur, fr);
1359                         }
1360                         */
1361                         if (cur.selection())
1362                                 cutSelection(cur, false);
1363                         cur.insert(inset);
1364                         cur.forceBufferUpdate();
1365                         if (inset->editable() && inset->asInsetText())
1366                                 inset->edit(cur, true);
1367                         else
1368                                 cur.posForward();
1369
1370                         // trigger InstantPreview now
1371                         if (inset->lyxCode() == EXTERNAL_CODE) {
1372                                 InsetExternal & ins =
1373                                         static_cast<InsetExternal &>(*inset);
1374                                 ins.updatePreview();
1375                         }
1376                 }
1377
1378                 break;
1379         }
1380
1381         case LFUN_INSET_DISSOLVE: {
1382                 if (dissolveInset(cur)) {
1383                         needsUpdate = true;
1384                         cur.forceBufferUpdate();
1385                 }
1386                 break;
1387         }
1388
1389         case LFUN_INSET_SPLIT: {
1390                 if (splitInset(cur)) {
1391                         needsUpdate = true;
1392                         cur.forceBufferUpdate();
1393                 }
1394                 break;
1395         }
1396
1397         case LFUN_GRAPHICS_SET_GROUP: {
1398                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1399                 if (!ins)
1400                         break;
1401
1402                 cur.recordUndo();
1403
1404                 string id = to_utf8(cmd.argument());
1405                 string grp = graphics::getGroupParams(bv->buffer(), id);
1406                 InsetGraphicsParams tmp, inspar = ins->getParams();
1407
1408                 if (id.empty())
1409                         inspar.groupId = to_utf8(cmd.argument());
1410                 else {
1411                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1412                         tmp.filename = inspar.filename;
1413                         inspar = tmp;
1414                 }
1415
1416                 ins->setParams(inspar);
1417                 break;
1418         }
1419
1420         case LFUN_SPACE_INSERT:
1421                 if (cur.paragraph().layout().free_spacing)
1422                         insertChar(cur, ' ');
1423                 else {
1424                         doInsertInset(cur, this, cmd, false, false);
1425                         cur.posForward();
1426                 }
1427                 moveCursor(cur, false);
1428                 break;
1429
1430         case LFUN_SPECIALCHAR_INSERT: {
1431                 string const name = to_utf8(cmd.argument());
1432                 if (name == "hyphenation")
1433                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1434                 else if (name == "allowbreak")
1435                         specialChar(cur, InsetSpecialChar::ALLOWBREAK);
1436                 else if (name == "ligature-break")
1437                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1438                 else if (name == "slash")
1439                         specialChar(cur, InsetSpecialChar::SLASH);
1440                 else if (name == "nobreakdash")
1441                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1442                 else if (name == "dots")
1443                         specialChar(cur, InsetSpecialChar::LDOTS);
1444                 else if (name == "end-of-sentence")
1445                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1446                 else if (name == "menu-separator")
1447                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1448                 else if (name == "lyx")
1449                         specialChar(cur, InsetSpecialChar::PHRASE_LYX);
1450                 else if (name == "tex")
1451                         specialChar(cur, InsetSpecialChar::PHRASE_TEX);
1452                 else if (name == "latex")
1453                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX);
1454                 else if (name == "latex2e")
1455                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX2E);
1456                 else if (name.empty())
1457                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1458                 else
1459                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1460                 break;
1461         }
1462
1463         case LFUN_IPAMACRO_INSERT: {
1464                 string const arg = cmd.getArg(0);
1465                 if (arg == "deco") {
1466                         // Open the inset, and move the current selection
1467                         // inside it.
1468                         doInsertInset(cur, this, cmd, true, true);
1469                         cur.posForward();
1470                         // Some insets are numbered, others are shown in the outline pane so
1471                         // let's update the labels and the toc backend.
1472                         cur.forceBufferUpdate();
1473                         break;
1474                 }
1475                 if (arg == "tone-falling")
1476                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1477                 else if (arg == "tone-rising")
1478                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1479                 else if (arg == "tone-high-rising")
1480                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1481                 else if (arg == "tone-low-rising")
1482                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1483                 else if (arg == "tone-high-rising-falling")
1484                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1485                 else if (arg.empty())
1486                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1487                 else
1488                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1489                 break;
1490         }
1491
1492         case LFUN_WORD_UPCASE:
1493                 changeCase(cur, text_uppercase, cmd.getArg(0) == "partial");
1494                 break;
1495
1496         case LFUN_WORD_LOWCASE:
1497                 changeCase(cur, text_lowercase, cmd.getArg(0) == "partial");
1498                 break;
1499
1500         case LFUN_WORD_CAPITALIZE:
1501                 changeCase(cur, text_capitalization, cmd.getArg(0) == "partial");
1502                 break;
1503
1504         case LFUN_CHARS_TRANSPOSE:
1505                 charsTranspose(cur);
1506                 break;
1507
1508         case LFUN_PASTE: {
1509                 cur.message(_("Paste"));
1510                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), break);
1511                 cap::replaceSelection(cur);
1512
1513                 // without argument?
1514                 string const arg = to_utf8(cmd.argument());
1515                 if (arg.empty()) {
1516                         bool tryGraphics = true;
1517                         if (theClipboard().isInternal())
1518                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1519                         else if (theClipboard().hasTextContents()) {
1520                                 if (pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1521                                                        !cur.paragraph().parbreakIsNewline(),
1522                                                            Clipboard::AnyTextType))
1523                                         tryGraphics = false;
1524                         }
1525                         if (tryGraphics && theClipboard().hasGraphicsContents())
1526                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1527                 } else if (isStrUnsignedInt(arg)) {
1528                         // we have a numerical argument
1529                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1530                                        convert<unsigned int>(arg));
1531                 } else if (arg == "html" || arg == "latex") {
1532                         Clipboard::TextType type = (arg == "html") ?
1533                                 Clipboard::HtmlTextType : Clipboard::LaTeXTextType;
1534                         pasteClipboardText(cur, bv->buffer().errorList("Paste"), true, type);
1535                 } else {
1536                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1537                         if (arg == "pdf")
1538                                 type = Clipboard::PdfGraphicsType;
1539                         else if (arg == "png")
1540                                 type = Clipboard::PngGraphicsType;
1541                         else if (arg == "jpeg")
1542                                 type = Clipboard::JpegGraphicsType;
1543                         else if (arg == "linkback")
1544                                 type = Clipboard::LinkBackGraphicsType;
1545                         else if (arg == "emf")
1546                                 type = Clipboard::EmfGraphicsType;
1547                         else if (arg == "wmf")
1548                                 type = Clipboard::WmfGraphicsType;
1549                         else
1550                                 // we also check in getStatus()
1551                                 LYXERR0("Unrecognized graphics type: " << arg);
1552
1553                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1554                 }
1555
1556                 bv->buffer().errors("Paste");
1557                 bv->buffer().updatePreviews(); // bug 11619
1558                 cur.clearSelection(); // bug 393
1559                 cur.finishUndo();
1560                 break;
1561         }
1562
1563         case LFUN_CUT:
1564                 cutSelection(cur, true);
1565                 cur.message(_("Cut"));
1566                 break;
1567
1568         case LFUN_SERVER_GET_XY:
1569                 cur.message(from_utf8(
1570                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1571                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1572                 break;
1573
1574         case LFUN_SERVER_SET_XY: {
1575                 int x = 0;
1576                 int y = 0;
1577                 istringstream is(to_utf8(cmd.argument()));
1578                 is >> x >> y;
1579                 if (!is)
1580                         lyxerr << "SETXY: Could not parse coordinates in '"
1581                                << to_utf8(cmd.argument()) << endl;
1582                 else
1583                         tm->setCursorFromCoordinates(cur, x, y);
1584                 break;
1585         }
1586
1587         case LFUN_SERVER_GET_LAYOUT:
1588                 cur.message(cur.paragraph().layout().name());
1589                 break;
1590
1591         case LFUN_LAYOUT:
1592         case LFUN_LAYOUT_TOGGLE: {
1593                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
1594                 docstring req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
1595                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(req_layout));
1596
1597                 docstring layout = resolveLayout(req_layout, cur);
1598                 if (layout.empty()) {
1599                         cur.errorMessage(from_utf8(N_("Layout ")) + req_layout +
1600                                 from_utf8(N_(" not known")));
1601                         break;
1602                 }
1603
1604                 docstring const old_layout = cur.paragraph().layout().name();
1605                 bool change_layout = !isAlreadyLayout(layout, cur);
1606
1607                 if (cmd.action() == LFUN_LAYOUT_TOGGLE && !change_layout) {
1608                         change_layout = true;
1609                         layout = resolveLayout(docstring(), cur);
1610                 }
1611
1612                 if (change_layout) {
1613                         setLayout(cur, layout);
1614                         if (cur.pit() > 0 && !ignoreautonests) {
1615                                 pit_type prev_pit = cur.pit() - 1;
1616                                 depth_type const cur_depth = pars_[cur.pit()].getDepth();
1617                                 // Scan for the previous par on same nesting level
1618                                 while (prev_pit > 0 && pars_[prev_pit].getDepth() > cur_depth)
1619                                         --prev_pit;
1620                                 set<docstring> const & autonests =
1621                                                 pars_[prev_pit].layout().autonests();
1622                                 set<docstring> const & autonested =
1623                                                 pars_[cur.pit()].layout().isAutonestedBy();
1624                                 if (autonests.find(layout) != autonests.end()
1625                                                 || autonested.find(old_layout) != autonested.end())
1626                                         lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1627                         }
1628                 }
1629
1630                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1631                 bool inautoarg = false;
1632                 for (auto const & la_pair : tclass[layout].args()) {
1633                         Layout::latexarg const & arg = la_pair.second;
1634                         if (arg.autoinsert) {
1635                                 // If we had already inserted an arg automatically,
1636                                 // leave this now in order to insert the next one.
1637                                 if (inautoarg) {
1638                                         cur.leaveInset(cur.inset());
1639                                         cur.posForward();
1640                                 }
1641                                 FuncRequest const cmd2(LFUN_ARGUMENT_INSERT, la_pair.first);
1642                                 lyx::dispatch(cmd2);
1643                                 inautoarg = true;
1644                         }
1645                 }
1646
1647                 break;
1648         }
1649
1650         case LFUN_ENVIRONMENT_SPLIT: {
1651                 bool const outer = cmd.argument() == "outer";
1652                 bool const previous = cmd.argument() == "previous";
1653                 bool const before = cmd.argument() == "before";
1654                 bool const normal = cmd.argument().empty();
1655                 Paragraph const & para = cur.paragraph();
1656                 docstring layout;
1657                 if (para.layout().isEnvironment())
1658                         layout = para.layout().name();
1659                 depth_type split_depth = cur.paragraph().params().depth();
1660                 vector<depth_type> nextpars_depth;
1661                 if (outer || previous) {
1662                         // check if we have an environment in our scope
1663                         pit_type pit = cur.pit();
1664                         Paragraph cpar = pars_[pit];
1665                         while (true) {
1666                                 if (pit == 0)
1667                                         break;
1668                                 --pit;
1669                                 cpar = pars_[pit];
1670                                 if (layout.empty() && previous
1671                                     && cpar.layout().isEnvironment()
1672                                     && cpar.params().depth() <= split_depth)
1673                                         layout = cpar.layout().name();
1674                                 if (cpar.params().depth() < split_depth
1675                                     && cpar.layout().isEnvironment()) {
1676                                                 if (!previous)
1677                                                         layout = cpar.layout().name();
1678                                                 split_depth = cpar.params().depth();
1679                                 }
1680                                 if (cpar.params().depth() == 0)
1681                                         break;
1682                         }
1683                 }
1684                 if ((outer || normal) && cur.pit() < cur.lastpit()) {
1685                         // save nesting of following paragraphs if they are deeper
1686                         // or same depth
1687                         pit_type offset = 1;
1688                         depth_type cur_depth = pars_[cur.pit()].params().depth();
1689                         while (cur.pit() + offset <= cur.lastpit()) {
1690                                 Paragraph cpar = pars_[cur.pit() + offset];
1691                                 depth_type nextpar_depth = cpar.params().depth();
1692                                 if (cur_depth <= nextpar_depth && nextpar_depth > 0) {
1693                                         nextpars_depth.push_back(nextpar_depth);
1694                                         cur_depth = nextpar_depth;
1695                                         ++offset;
1696                                 } else
1697                                         break;
1698                         }
1699                 }
1700                 if (before)
1701                         cur.top().setPitPos(cur.pit(), 0);
1702                 if (before || cur.pos() > 0)
1703                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1704                 else if (previous && cur.nextInset() && cur.nextInset()->lyxCode() == SEPARATOR_CODE)
1705                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1706                 if (outer) {
1707                         while (cur.paragraph().params().depth() > split_depth)
1708                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
1709                 }
1710                 DocumentClass const & tc = bv->buffer().params().documentClass();
1711                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
1712                                           + from_ascii("\" ignoreautonests")));
1713                 // FIXME: Bibitem mess!
1714                 if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
1715                         lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
1716                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1717                 if (before) {
1718                         cur.backwardPos();
1719                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1720                         while (cur.paragraph().params().depth() < split_depth)
1721                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1722                 }
1723                 else
1724                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1725                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1726                 if ((outer || normal) && !nextpars_depth.empty()) {
1727                         // restore nesting of following paragraphs
1728                         DocIterator scur = cur;
1729                         depth_type max_depth = cur.paragraph().params().depth() + 1;
1730                         for (auto nextpar_depth : nextpars_depth) {
1731                                 cur.forwardPar();
1732                                 while (cur.paragraph().params().depth() < min(nextpar_depth, max_depth)) {
1733                                         depth_type const olddepth = cur.paragraph().params().depth();
1734                                         lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1735                                         if (olddepth == cur.paragraph().params().depth())
1736                                                 // leave loop if no incrementation happens
1737                                                 break;
1738                                 }
1739                                 max_depth = cur.paragraph().params().depth() + 1;
1740                         }
1741                         cur.setCursor(scur);
1742                 }
1743
1744                 break;
1745         }
1746
1747         case LFUN_CLIPBOARD_PASTE:
1748                 cap::replaceSelection(cur);
1749                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1750                                cmd.argument() == "paragraph");
1751                 bv->buffer().errors("Paste");
1752                 break;
1753
1754         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1755                 cap::replaceSelection(cur);
1756                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1757                 break;
1758
1759         case LFUN_PRIMARY_SELECTION_PASTE:
1760                 cap::replaceSelection(cur);
1761                 pasteString(cur, theSelection().get(),
1762                             cmd.argument() == "paragraph");
1763                 break;
1764
1765         case LFUN_SELECTION_PASTE:
1766                 // Copy the selection buffer to the clipboard stack,
1767                 // because we want it to appear in the "Edit->Paste
1768                 // recent" menu.
1769                 cap::replaceSelection(cur);
1770                 cap::copySelectionToStack();
1771                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1772                 bv->buffer().errors("Paste");
1773                 break;
1774
1775         case LFUN_QUOTE_INSERT: {
1776                 cap::replaceSelection(cur);
1777                 cur.recordUndo();
1778
1779                 Paragraph const & par = cur.paragraph();
1780                 pos_type pos = cur.pos();
1781                 // Ignore deleted text before cursor
1782                 while (pos > 0 && par.isDeleted(pos - 1))
1783                         --pos;
1784
1785                 bool const inner = (cmd.getArg(0) == "single" || cmd.getArg(0) == "inner");
1786
1787                 // Guess quote side.
1788                 // A space triggers an opening quote. This is passed if the preceding
1789                 // char/inset is a space or at paragraph start.
1790                 char_type c = ' ';
1791                 if (pos > 0 && !par.isSpace(pos - 1)) {
1792                         if (cur.prevInset() && cur.prevInset()->lyxCode() == QUOTE_CODE) {
1793                                 // If an opening double quotation mark precedes, and this
1794                                 // is a single quote, make it opening as well
1795                                 InsetQuotes & ins =
1796                                         static_cast<InsetQuotes &>(*cur.prevInset());
1797                                 string const type = ins.getType();
1798                                 if (!suffixIs(type, "ld") || !inner)
1799                                         c = par.getChar(pos - 1);
1800                         }
1801                         else if (!cur.prevInset()
1802                             || (cur.prevInset() && cur.prevInset()->isChar()))
1803                                 // If a char precedes, pass that and let InsetQuote decide
1804                                 c = par.getChar(pos - 1);
1805                         else {
1806                                 while (pos > 0) {
1807                                         if (par.getInset(pos - 1)
1808                                             && !par.getInset(pos - 1)->isPartOfTextSequence()) {
1809                                                 // skip "invisible" insets
1810                                                 --pos;
1811                                                 continue;
1812                                         }
1813                                         c = par.getChar(pos - 1);
1814                                         break;
1815                                 }
1816                         }
1817                 }
1818                 QuoteLevel const quote_level = inner
1819                                 ? QuoteLevel::Secondary : QuoteLevel::Primary;
1820                 cur.insert(new InsetQuotes(cur.buffer(), c, quote_level, cmd.getArg(1), cmd.getArg(2)));
1821                 cur.buffer()->updateBuffer();
1822                 cur.posForward();
1823                 break;
1824         }
1825
1826         case LFUN_MOUSE_TRIPLE:
1827                 if (cmd.button() == mouse_button::button1) {
1828                         if (cur.pos() > 0)
1829                                 setCursor(cur, cur.pit(), 0);
1830                         bv->cursor() = cur;
1831                         cur.resetAnchor();
1832                         if (cur.pos() < cur.lastpos())
1833                                 setCursor(cur, cur.pit(), cur.lastpos());
1834                         cur.setSelection();
1835                         bv->cursor() = cur;
1836                 }
1837                 break;
1838
1839         case LFUN_MOUSE_DOUBLE:
1840                 if (cmd.button() == mouse_button::button1) {
1841                         selectWord(cur, WHOLE_WORD);
1842                         bv->cursor() = cur;
1843                 }
1844                 break;
1845
1846         // Single-click on work area
1847         case LFUN_MOUSE_PRESS: {
1848                 // We are not marking a selection with the keyboard in any case.
1849                 Cursor & bvcur = cur.bv().cursor();
1850                 bvcur.setMark(false);
1851                 switch (cmd.button()) {
1852                 case mouse_button::button1:
1853                         if (!bvcur.selection())
1854                                 // Set the cursor
1855                                 bvcur.resetAnchor();
1856                         if (!bv->mouseSetCursor(cur, cmd.modifier() == ShiftModifier))
1857                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1858                         // FIXME: move this to mouseSetCursor?
1859                         if (bvcur.wordSelection() && bvcur.inTexted())
1860                                 expandWordSel(bvcur);
1861                         break;
1862
1863                 case mouse_button::button2:
1864                         if (lyxrc.mouse_middlebutton_paste) {
1865                                 // Middle mouse pasting.
1866                                 bv->mouseSetCursor(cur);
1867                                 lyx::dispatch(
1868                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1869                                                     "selection-paste ; primary-selection-paste paragraph"));
1870                         }
1871                         cur.noScreenUpdate();
1872                         break;
1873
1874                 case mouse_button::button3: {
1875                         // Don't do anything if we right-click a
1876                         // selection, a context menu will popup.
1877                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1878                             && cur <= bvcur.selectionEnd()) {
1879                                 cur.noScreenUpdate();
1880                                 return;
1881                         }
1882                         if (!bv->mouseSetCursor(cur, false))
1883                                 cur.screenUpdateFlags(Update::FitCursor);
1884                         break;
1885                 }
1886
1887                 default:
1888                         break;
1889                 } // switch (cmd.button())
1890                 break;
1891         }
1892         case LFUN_MOUSE_MOTION: {
1893                 // Mouse motion with right or middle mouse do nothing for now.
1894                 if (cmd.button() != mouse_button::button1) {
1895                         cur.noScreenUpdate();
1896                         return;
1897                 }
1898                 // ignore motions deeper nested than the real anchor
1899                 Cursor & bvcur = cur.bv().cursor();
1900                 if (!bvcur.realAnchor().hasPart(cur)) {
1901                         cur.undispatched();
1902                         break;
1903                 }
1904                 CursorSlice old = bvcur.top();
1905
1906                 int const wh = bv->workHeight();
1907                 int const y = max(0, min(wh - 1, cmd.y()));
1908
1909                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1910                 cur.setTargetX(cmd.x());
1911                 // Don't allow selecting a separator inset
1912                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1913                         cur.posBackward();
1914                 if (cmd.y() >= wh)
1915                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1916                 else if (cmd.y() < 0)
1917                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1918                 // This is to allow jumping over large insets
1919                 if (cur.top() == old) {
1920                         if (cmd.y() >= wh)
1921                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1922                         else if (cmd.y() < 0)
1923                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1924                 }
1925                 // We continue with our existing selection or start a new one, so don't
1926                 // reset the anchor.
1927                 bvcur.setCursor(cur);
1928                 if (bvcur.wordSelection() && bvcur.inTexted())
1929                         expandWordSel(bvcur);
1930                 bvcur.selection(true);
1931                 bvcur.setCurrentFont();
1932                 if (cur.top() == old) {
1933                         // We didn't move one iota, so no need to update the screen.
1934                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1935                         //cur.noScreenUpdate();
1936                         return;
1937                 }
1938                 break;
1939         }
1940
1941         case LFUN_MOUSE_RELEASE:
1942                 switch (cmd.button()) {
1943                 case mouse_button::button1:
1944                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1945                         // If there is a new selection, update persistent selection;
1946                         // otherwise, single click does not clear persistent selection
1947                         // buffer.
1948                         if (cur.selection()) {
1949                                 // Finish selection. If double click,
1950                                 // cur is moved to the end of word by
1951                                 // selectWord but bvcur is current
1952                                 // mouse position.
1953                                 cur.bv().cursor().setSelection();
1954                                 // We might have removed an empty but drawn selection
1955                                 // (probably a margin)
1956                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1957                         } else
1958                                 cur.noScreenUpdate();
1959                         // FIXME: We could try to handle drag and drop of selection here.
1960                         return;
1961
1962                 case mouse_button::button2:
1963                         // Middle mouse pasting is handled at mouse press time,
1964                         // see LFUN_MOUSE_PRESS.
1965                         cur.noScreenUpdate();
1966                         return;
1967
1968                 case mouse_button::button3:
1969                         // Cursor was set at LFUN_MOUSE_PRESS time.
1970                         // FIXME: If there is a selection we could try to handle a special
1971                         // drag & drop context menu.
1972                         cur.noScreenUpdate();
1973                         return;
1974
1975                 case mouse_button::none:
1976                 case mouse_button::button4:
1977                 case mouse_button::button5:
1978                         break;
1979                 } // switch (cmd.button())
1980
1981                 break;
1982
1983         case LFUN_SELF_INSERT: {
1984                 if (cmd.argument().empty())
1985                         break;
1986
1987                 // Automatically delete the currently selected
1988                 // text and replace it with what is being
1989                 // typed in now. Depends on lyxrc settings
1990                 // "auto_region_delete", which defaults to
1991                 // true (on).
1992
1993                 if (lyxrc.auto_region_delete && cur.selection()) {
1994                         cutSelection(cur, false);
1995                         cur.setCurrentFont();
1996                 }
1997                 cur.clearSelection();
1998
1999                 for (char_type c : cmd.argument())
2000                         bv->translateAndInsert(c, this, cur);
2001
2002                 cur.resetAnchor();
2003                 moveCursor(cur, false);
2004                 cur.markNewWordPosition();
2005                 bv->bookmarkEditPosition();
2006                 break;
2007         }
2008
2009         case LFUN_HREF_INSERT: {
2010                 docstring content = cmd.argument();
2011                 if (content.empty() && cur.selection())
2012                         content = cur.selectionAsString(false);
2013
2014                 InsetCommandParams p(HYPERLINK_CODE);
2015                 if (!content.empty()){
2016                         // if it looks like a link, we'll put it as target,
2017                         // otherwise as name (bug #8792).
2018
2019                         // We can't do:
2020                         //   regex_match(to_utf8(content), matches, link_re)
2021                         // because smatch stores pointers to the substrings rather
2022                         // than making copies of them. And those pointers become
2023                         // invalid after regex_match returns, since it is then
2024                         // being given a temporary object. (Thanks to Georg for
2025                         // figuring that out.)
2026                         regex const link_re("^([a-z]+):.*");
2027                         smatch matches;
2028                         string const c = to_utf8(lowercase(content));
2029
2030                         if (c.substr(0,7) == "mailto:") {
2031                                 p["target"] = content;
2032                                 p["type"] = from_ascii("mailto:");
2033                         } else if (regex_match(c, matches, link_re)) {
2034                                 p["target"] = content;
2035                                 string protocol = matches.str(1);
2036                                 if (protocol == "file")
2037                                         p["type"] = from_ascii("file:");
2038                         } else
2039                                 p["name"] = content;
2040                 }
2041                 string const data = InsetCommand::params2string(p);
2042
2043                 // we need to have a target. if we already have one, then
2044                 // that gets used at the default for the name, too, which
2045                 // is probably what is wanted.
2046                 if (p["target"].empty()) {
2047                         bv->showDialog("href", data);
2048                 } else {
2049                         FuncRequest fr(LFUN_INSET_INSERT, data);
2050                         dispatch(cur, fr);
2051                 }
2052                 break;
2053         }
2054
2055         case LFUN_LABEL_INSERT: {
2056                 InsetCommandParams p(LABEL_CODE);
2057                 // Try to generate a valid label
2058                 p["name"] = (cmd.argument().empty()) ?
2059                         cur.getPossibleLabel() :
2060                         cmd.argument();
2061                 string const data = InsetCommand::params2string(p);
2062
2063                 if (cmd.argument().empty()) {
2064                         bv->showDialog("label", data);
2065                 } else {
2066                         FuncRequest fr(LFUN_INSET_INSERT, data);
2067                         dispatch(cur, fr);
2068                 }
2069                 break;
2070         }
2071
2072         case LFUN_INFO_INSERT: {
2073                 if (cmd.argument().empty()) {
2074                         bv->showDialog("info", cur.current_font.language()->lang());
2075                 } else {
2076                         Inset * inset;
2077                         inset = createInset(cur.buffer(), cmd);
2078                         if (!inset)
2079                                 break;
2080                         cur.recordUndo();
2081                         insertInset(cur, inset);
2082                         cur.forceBufferUpdate();
2083                         cur.posForward();
2084                 }
2085                 break;
2086         }
2087         case LFUN_CAPTION_INSERT:
2088         case LFUN_FOOTNOTE_INSERT:
2089         case LFUN_NOTE_INSERT:
2090         case LFUN_BOX_INSERT:
2091         case LFUN_BRANCH_INSERT:
2092         case LFUN_PHANTOM_INSERT:
2093         case LFUN_ERT_INSERT:
2094         case LFUN_INDEXMACRO_INSERT:
2095         case LFUN_LISTING_INSERT:
2096         case LFUN_MARGINALNOTE_INSERT:
2097         case LFUN_ARGUMENT_INSERT:
2098         case LFUN_INDEX_INSERT:
2099         case LFUN_PREVIEW_INSERT:
2100         case LFUN_SCRIPT_INSERT:
2101         case LFUN_IPA_INSERT: {
2102                 // Indexes reset font formatting (#11961)
2103                 bool const resetfont = cmd.action() == LFUN_INDEX_INSERT;
2104                 // Open the inset, and move the current selection
2105                 // inside it.
2106                 doInsertInset(cur, this, cmd, true, true, resetfont);
2107                 cur.posForward();
2108                 cur.setCurrentFont();
2109                 // Some insets are numbered, others are shown in the outline pane so
2110                 // let's update the labels and the toc backend.
2111                 cur.forceBufferUpdate();
2112                 break;
2113         }
2114
2115         case LFUN_FLEX_INSERT: {
2116                 // Open the inset, and move the current selection
2117                 // inside it.
2118                 bool const sel = cur.selection();
2119                 doInsertInset(cur, this, cmd, true, true);
2120                 // Insert auto-insert arguments
2121                 bool autoargs = false, inautoarg = false;
2122                 Layout::LaTeXArgMap args = cur.inset().getLayout().args();
2123                 for (auto const & argt : args) {
2124                         Layout::latexarg arg = argt.second;
2125                         if (!inautoarg && arg.insertonnewline && cur.pos() > 0) {
2126                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2127                                 lyx::dispatch(cmd2);
2128                         }
2129                         if (arg.autoinsert) {
2130                                 // The cursor might have been invalidated by the replaceSelection.
2131                                 cur.buffer()->changed(true);
2132                                 // If we had already inserted an arg automatically,
2133                                 // leave this now in order to insert the next one.
2134                                 if (inautoarg) {
2135                                         cur.leaveInset(cur.inset());
2136                                         cur.setCurrentFont();
2137                                         cur.posForward();
2138                                         if (arg.insertonnewline && cur.pos() > 0) {
2139                                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2140                                                 lyx::dispatch(cmd2);
2141                                         }
2142                                 }
2143                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, argt.first);
2144                                 lyx::dispatch(cmd2);
2145                                 autoargs = true;
2146                                 inautoarg = true;
2147                         }
2148                 }
2149                 if (!autoargs) {
2150                         if (sel)
2151                                 cur.leaveInset(cur.inset());
2152                         cur.posForward();
2153                 }
2154                 // Some insets are numbered, others are shown in the outline pane so
2155                 // let's update the labels and the toc backend.
2156                 cur.forceBufferUpdate();
2157                 break;
2158         }
2159
2160         case LFUN_TABULAR_INSERT: {
2161                 // if there were no arguments, just open the dialog
2162                 if (cmd.argument().empty()) {
2163                         bv->showDialog("tabularcreate");
2164                         break;
2165                 } else if (cur.buffer()->masterParams().tablestyle != "default"
2166                            || bv->buffer().params().documentClass().tablestyle() != "default") {
2167                         string tabstyle = cur.buffer()->masterParams().tablestyle;
2168                         if (tabstyle == "default")
2169                                 tabstyle = bv->buffer().params().documentClass().tablestyle();
2170                         if (!libFileSearch("tabletemplates", tabstyle + ".lyx").empty()) {
2171                                 FuncRequest fr(LFUN_TABULAR_STYLE_INSERT,
2172                                                tabstyle + " " + to_ascii(cmd.argument()));
2173                                 lyx::dispatch(fr);
2174                                 break;
2175                         } else
2176                                 // Unknown style. Report and fall back to default.
2177                                 cur.errorMessage(from_utf8(N_("Table Style ")) + from_utf8(tabstyle) +
2178                                                      from_utf8(N_(" not known")));
2179                 }
2180                 if (doInsertInset(cur, this, cmd, false, true))
2181                         cur.posForward();
2182                 break;
2183         }
2184
2185         case LFUN_TABULAR_STYLE_INSERT: {
2186                 string const style = cmd.getArg(0);
2187                 string const rows = cmd.getArg(1);
2188                 string const cols = cmd.getArg(2);
2189                 if (cols.empty() || !isStrInt(cols)
2190                     || rows.empty() || !isStrInt(rows))
2191                         break;
2192                 int const r = convert<int>(rows);
2193                 int const c = convert<int>(cols);
2194
2195                 string suffix;
2196                 if (r == 1)
2197                         suffix = "_1x1";
2198                 else if (r == 2)
2199                         suffix = "_1x2";
2200                 FileName const tabstyle = libFileSearch("tabletemplates",
2201                                                         style + suffix + ".lyx", "lyx");
2202                 if (tabstyle.empty())
2203                             break;
2204                 UndoGroupHelper ugh(cur.buffer());
2205                 cur.recordUndo();
2206                 FuncRequest cmd2(LFUN_FILE_INSERT, tabstyle.absFileName() + " ignorelang");
2207                 lyx::dispatch(cmd2);
2208                 // go into table
2209                 cur.backwardPos();
2210                 if (r > 2) {
2211                         // move one cell up to middle cell
2212                         cur.up();
2213                         // add the missing rows
2214                         int const addrows = r - 3;
2215                         for (int i = 0 ; i < addrows ; ++i) {
2216                                 FuncRequest fr(LFUN_TABULAR_FEATURE, "append-row");
2217                                 lyx::dispatch(fr);
2218                         }
2219                 }
2220                 // add the missing columns
2221                 int const addcols = c - 1;
2222                 for (int i = 0 ; i < addcols ; ++i) {
2223                         FuncRequest fr(LFUN_TABULAR_FEATURE, "append-column");
2224                         lyx::dispatch(fr);
2225                 }
2226                 if (r > 1)
2227                         // go to first cell
2228                         cur.up();
2229                 break;
2230         }
2231
2232         case LFUN_FLOAT_INSERT:
2233         case LFUN_FLOAT_WIDE_INSERT:
2234         case LFUN_WRAP_INSERT: {
2235                 // will some content be moved into the inset?
2236                 bool const content = cur.selection();
2237                 // does the content consist of multiple paragraphs?
2238                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2239
2240                 doInsertInset(cur, this, cmd, true, true);
2241                 cur.posForward();
2242
2243                 // If some single-par content is moved into the inset,
2244                 // doInsertInset puts the cursor outside the inset.
2245                 // To insert the caption we put it back into the inset.
2246                 // FIXME cleanup doInsertInset to avoid such dances!
2247                 if (content && singlepar)
2248                         cur.backwardPos();
2249
2250                 ParagraphList & pars = cur.text()->paragraphs();
2251
2252                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2253
2254                 // add a separate paragraph for the caption inset
2255                 pars.push_back(Paragraph());
2256                 pars.back().setInsetOwner(&cur.text()->inset());
2257                 pars.back().setPlainOrDefaultLayout(tclass);
2258                 int cap_pit = pars.size() - 1;
2259
2260                 // if an empty inset was created, we create an additional empty
2261                 // paragraph at the bottom so that the user can choose where to put
2262                 // the graphics (or table).
2263                 if (!content) {
2264                         pars.push_back(Paragraph());
2265                         pars.back().setInsetOwner(&cur.text()->inset());
2266                         pars.back().setPlainOrDefaultLayout(tclass);
2267                 }
2268
2269                 // reposition the cursor to the caption
2270                 cur.pit() = cap_pit;
2271                 cur.pos() = 0;
2272                 // FIXME: This Text/Cursor dispatch handling is a mess!
2273                 // We cannot use Cursor::dispatch here it needs access to up to
2274                 // date metrics.
2275                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2276                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2277                 cur.forceBufferUpdate();
2278                 cur.screenUpdateFlags(Update::Force);
2279                 // FIXME: When leaving the Float (or Wrap) inset we should
2280                 // delete any empty paragraph left above or below the
2281                 // caption.
2282                 break;
2283         }
2284
2285         case LFUN_NOMENCL_INSERT: {
2286                 InsetCommandParams p(NOMENCL_CODE);
2287                 if (cmd.argument().empty()) {
2288                         p["symbol"] =
2289                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2290                         cur.clearSelection();
2291                 } else
2292                         p["symbol"] = cmd.argument();
2293                 string const data = InsetCommand::params2string(p);
2294                 bv->showDialog("nomenclature", data);
2295                 break;
2296         }
2297
2298         case LFUN_INDEX_PRINT: {
2299                 InsetCommandParams p(INDEX_PRINT_CODE);
2300                 if (cmd.argument().empty())
2301                         p["type"] = from_ascii("idx");
2302                 else
2303                         p["type"] = cmd.argument();
2304                 string const data = InsetCommand::params2string(p);
2305                 FuncRequest fr(LFUN_INSET_INSERT, data);
2306                 dispatch(cur, fr);
2307                 break;
2308         }
2309
2310         case LFUN_NOMENCL_PRINT:
2311         case LFUN_NEWPAGE_INSERT:
2312                 // do nothing fancy
2313                 doInsertInset(cur, this, cmd, false, false);
2314                 cur.posForward();
2315                 break;
2316
2317         case LFUN_SEPARATOR_INSERT: {
2318                 doInsertInset(cur, this, cmd, false, false);
2319                 cur.posForward();
2320                 // remove a following space
2321                 Paragraph & par = cur.paragraph();
2322                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2323                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2324                 break;
2325         }
2326
2327         case LFUN_DEPTH_DECREMENT:
2328                 changeDepth(cur, DEC_DEPTH);
2329                 break;
2330
2331         case LFUN_DEPTH_INCREMENT:
2332                 changeDepth(cur, INC_DEPTH);
2333                 break;
2334
2335         case LFUN_REGEXP_MODE:
2336                 regexpDispatch(cur, cmd);
2337                 break;
2338
2339         case LFUN_MATH_MODE: {
2340                 if (cmd.argument() == "on" || cmd.argument() == "") {
2341                         // don't pass "on" as argument
2342                         // (it would appear literally in the first cell)
2343                         docstring sel = cur.selectionAsString(false);
2344                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2345                         // create a macro template if we see "\\newcommand" somewhere, and
2346                         // an ordinary formula otherwise
2347                         if (!sel.empty()
2348                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2349                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2350                                         || sel.find(from_ascii("\\def")) != string::npos)
2351                                 && macro->fromString(sel)) {
2352                                 cur.recordUndo();
2353                                 replaceSelection(cur);
2354                                 cur.insert(macro);
2355                         } else {
2356                                 // no meaningful macro template was found
2357                                 delete macro;
2358                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2359                         }
2360                 } else
2361                         // The argument is meaningful
2362                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2363                         // has a different meaning in math mode
2364                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2365                 break;
2366         }
2367
2368         case LFUN_MATH_MACRO:
2369                 if (cmd.argument().empty())
2370                         cur.errorMessage(from_utf8(N_("Missing argument")));
2371                 else {
2372                         cur.recordUndo();
2373                         string s = to_utf8(cmd.argument());
2374                         string const s1 = token(s, ' ', 1);
2375                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2376                         string const s2 = token(s, ' ', 2);
2377                         MacroType type = MacroTypeNewcommand;
2378                         if (s2 == "def")
2379                                 type = MacroTypeDef;
2380                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2381                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2382                         inset->setBuffer(bv->buffer());
2383                         insertInset(cur, inset);
2384
2385                         // enter macro inset and select the name
2386                         cur.push(*inset);
2387                         cur.top().pos() = cur.top().lastpos();
2388                         cur.resetAnchor();
2389                         cur.selection(true);
2390                         cur.top().pos() = 0;
2391                 }
2392                 break;
2393
2394         case LFUN_MATH_DISPLAY:
2395         case LFUN_MATH_SUBSCRIPT:
2396         case LFUN_MATH_SUPERSCRIPT:
2397         case LFUN_MATH_INSERT:
2398         case LFUN_MATH_AMS_MATRIX:
2399         case LFUN_MATH_MATRIX:
2400         case LFUN_MATH_DELIM:
2401         case LFUN_MATH_BIGDELIM:
2402                 mathDispatch(cur, cmd);
2403                 break;
2404
2405         case LFUN_FONT_EMPH: {
2406                 Font font(ignore_font, ignore_language);
2407                 font.fontInfo().setEmph(FONT_TOGGLE);
2408                 toggleAndShow(cur, this, font);
2409                 break;
2410         }
2411
2412         case LFUN_FONT_ITAL: {
2413                 Font font(ignore_font, ignore_language);
2414                 font.fontInfo().setShape(ITALIC_SHAPE);
2415                 toggleAndShow(cur, this, font);
2416                 break;
2417         }
2418
2419         case LFUN_FONT_BOLD:
2420         case LFUN_FONT_BOLDSYMBOL: {
2421                 Font font(ignore_font, ignore_language);
2422                 font.fontInfo().setSeries(BOLD_SERIES);
2423                 toggleAndShow(cur, this, font);
2424                 break;
2425         }
2426
2427         case LFUN_FONT_NOUN: {
2428                 Font font(ignore_font, ignore_language);
2429                 font.fontInfo().setNoun(FONT_TOGGLE);
2430                 toggleAndShow(cur, this, font);
2431                 break;
2432         }
2433
2434         case LFUN_FONT_TYPEWRITER: {
2435                 Font font(ignore_font, ignore_language);
2436                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2437                 toggleAndShow(cur, this, font);
2438                 break;
2439         }
2440
2441         case LFUN_FONT_SANS: {
2442                 Font font(ignore_font, ignore_language);
2443                 font.fontInfo().setFamily(SANS_FAMILY);
2444                 toggleAndShow(cur, this, font);
2445                 break;
2446         }
2447
2448         case LFUN_FONT_ROMAN: {
2449                 Font font(ignore_font, ignore_language);
2450                 font.fontInfo().setFamily(ROMAN_FAMILY);
2451                 toggleAndShow(cur, this, font);
2452                 break;
2453         }
2454
2455         case LFUN_FONT_DEFAULT: {
2456                 Font font(inherit_font, ignore_language);
2457                 toggleAndShow(cur, this, font);
2458                 break;
2459         }
2460
2461         case LFUN_FONT_STRIKEOUT: {
2462                 Font font(ignore_font, ignore_language);
2463                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2464                 toggleAndShow(cur, this, font);
2465                 break;
2466         }
2467
2468         case LFUN_FONT_CROSSOUT: {
2469                 Font font(ignore_font, ignore_language);
2470                 font.fontInfo().setXout(FONT_TOGGLE);
2471                 toggleAndShow(cur, this, font);
2472                 break;
2473         }
2474
2475         case LFUN_FONT_UNDERUNDERLINE: {
2476                 Font font(ignore_font, ignore_language);
2477                 font.fontInfo().setUuline(FONT_TOGGLE);
2478                 toggleAndShow(cur, this, font);
2479                 break;
2480         }
2481
2482         case LFUN_FONT_UNDERWAVE: {
2483                 Font font(ignore_font, ignore_language);
2484                 font.fontInfo().setUwave(FONT_TOGGLE);
2485                 toggleAndShow(cur, this, font);
2486                 break;
2487         }
2488
2489         case LFUN_FONT_UNDERLINE: {
2490                 Font font(ignore_font, ignore_language);
2491                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2492                 toggleAndShow(cur, this, font);
2493                 break;
2494         }
2495
2496         case LFUN_FONT_NO_SPELLCHECK: {
2497                 Font font(ignore_font, ignore_language);
2498                 font.fontInfo().setNoSpellcheck(FONT_TOGGLE);
2499                 toggleAndShow(cur, this, font);
2500                 break;
2501         }
2502
2503         case LFUN_FONT_SIZE: {
2504                 Font font(ignore_font, ignore_language);
2505                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2506                 toggleAndShow(cur, this, font);
2507                 break;
2508         }
2509
2510         case LFUN_LANGUAGE: {
2511                 string const lang_arg = cmd.getArg(0);
2512                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2513                 Language const * lang =
2514                         reset ? reset_language
2515                               : languages.getLanguage(lang_arg);
2516                 // we allow reset_language, which is 0, but only if it
2517                 // was requested via empty or "reset" arg.
2518                 if (!lang && !reset)
2519                         break;
2520                 bool const toggle = (cmd.getArg(1) != "set");
2521                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2522                 Font font(ignore_font, lang);
2523                 toggleAndShow(cur, this, font, toggle);
2524                 break;
2525         }
2526
2527         case LFUN_TEXTSTYLE_APPLY: {
2528                 unsigned int num = 0;
2529                 string const arg = to_utf8(cmd.argument());
2530                 // Argument?
2531                 if (!arg.empty()) {
2532                         if (isStrUnsignedInt(arg)) {
2533                                 num = convert<uint>(arg);
2534                                 if (num >= freeFonts.size()) {
2535                                         cur.message(_("Invalid argument (number exceeds stack size)!"));
2536                                         break;
2537                                 }
2538                         } else {
2539                                 cur.message(_("Invalid argument (must be a non-negative number)!"));
2540                                 break;
2541                         }
2542                 }
2543                 toggleAndShow(cur, this, freeFonts[num].second, toggleall);
2544                 cur.message(bformat(_("Text properties applied: %1$s"), freeFonts[num].first));
2545                 break;
2546         }
2547
2548         // Set the freefont using the contents of \param data dispatched from
2549         // the frontends and apply it at the current cursor location.
2550         case LFUN_TEXTSTYLE_UPDATE: {
2551                 Font font(ignore_font, ignore_language);
2552                 bool toggle;
2553                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2554                         docstring const props = font.stateText(&bv->buffer().params(), true);
2555                         freeFonts.push(make_pair(props, font));
2556                         toggleall = toggle;
2557                         toggleAndShow(cur, this, font, toggleall);
2558                         cur.message(bformat(_("Text properties applied: %1$s"), props));
2559                 } else
2560                         LYXERR0("Invalid argument of textstyle-update");
2561                 break;
2562         }
2563
2564         case LFUN_FINISHED_LEFT:
2565                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2566                 // We're leaving an inset, going left. If the inset is LTR, we're
2567                 // leaving from the front, so we should not move (remain at --- but
2568                 // not in --- the inset). If the inset is RTL, move left, without
2569                 // entering the inset itself; i.e., move to after the inset.
2570                 if (cur.paragraph().getFontSettings(
2571                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2572                         cursorVisLeft(cur, true);
2573                 break;
2574
2575         case LFUN_FINISHED_RIGHT:
2576                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2577                 // We're leaving an inset, going right. If the inset is RTL, we're
2578                 // leaving from the front, so we should not move (remain at --- but
2579                 // not in --- the inset). If the inset is LTR, move right, without
2580                 // entering the inset itself; i.e., move to after the inset.
2581                 if (!cur.paragraph().getFontSettings(
2582                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2583                         cursorVisRight(cur, true);
2584                 break;
2585
2586         case LFUN_FINISHED_BACKWARD:
2587                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2588                 cur.setCurrentFont();
2589                 break;
2590
2591         case LFUN_FINISHED_FORWARD:
2592                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2593                 ++cur.pos();
2594                 cur.setCurrentFont();
2595                 break;
2596
2597         case LFUN_LAYOUT_PARAGRAPH: {
2598                 string data;
2599                 params2string(cur.paragraph(), data);
2600                 data = "show\n" + data;
2601                 bv->showDialog("paragraph", data);
2602                 break;
2603         }
2604
2605         case LFUN_PARAGRAPH_UPDATE: {
2606                 string data;
2607                 params2string(cur.paragraph(), data);
2608
2609                 // Will the paragraph accept changes from the dialog?
2610                 bool const accept =
2611                         cur.inset().allowParagraphCustomization(cur.idx());
2612
2613                 data = "update " + convert<string>(accept) + '\n' + data;
2614                 bv->updateDialog("paragraph", data);
2615                 break;
2616         }
2617
2618         case LFUN_ACCENT_UMLAUT:
2619         case LFUN_ACCENT_CIRCUMFLEX:
2620         case LFUN_ACCENT_GRAVE:
2621         case LFUN_ACCENT_ACUTE:
2622         case LFUN_ACCENT_TILDE:
2623         case LFUN_ACCENT_PERISPOMENI:
2624         case LFUN_ACCENT_CEDILLA:
2625         case LFUN_ACCENT_MACRON:
2626         case LFUN_ACCENT_DOT:
2627         case LFUN_ACCENT_UNDERDOT:
2628         case LFUN_ACCENT_UNDERBAR:
2629         case LFUN_ACCENT_CARON:
2630         case LFUN_ACCENT_BREVE:
2631         case LFUN_ACCENT_TIE:
2632         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2633         case LFUN_ACCENT_CIRCLE:
2634         case LFUN_ACCENT_OGONEK:
2635                 theApp()->handleKeyFunc(cmd.action());
2636                 if (!cmd.argument().empty())
2637                         // FIXME: Are all these characters encoded in one byte in utf8?
2638                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2639                 cur.screenUpdateFlags(Update::FitCursor);
2640                 break;
2641
2642         case LFUN_FLOAT_LIST_INSERT: {
2643                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2644                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2645                         cur.recordUndo();
2646                         if (cur.selection())
2647                                 cutSelection(cur, false);
2648                         breakParagraph(cur);
2649
2650                         if (cur.lastpos() != 0) {
2651                                 cursorBackward(cur);
2652                                 breakParagraph(cur);
2653                         }
2654
2655                         docstring const laystr = cur.inset().usePlainLayout() ?
2656                                 tclass.plainLayoutName() :
2657                                 tclass.defaultLayoutName();
2658                         setLayout(cur, laystr);
2659                         ParagraphParameters p;
2660                         // FIXME If this call were replaced with one to clearParagraphParams(),
2661                         // then we could get rid of this method altogether.
2662                         setParagraphs(cur, p);
2663                         // FIXME This should be simplified when InsetFloatList takes a
2664                         // Buffer in its constructor.
2665                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2666                         ifl->setBuffer(bv->buffer());
2667                         insertInset(cur, ifl);
2668                         cur.posForward();
2669                 } else {
2670                         lyxerr << "Non-existent float type: "
2671                                << to_utf8(cmd.argument()) << endl;
2672                 }
2673                 break;
2674         }
2675
2676         case LFUN_CHANGE_ACCEPT: {
2677                 acceptOrRejectChanges(cur, ACCEPT);
2678                 break;
2679         }
2680
2681         case LFUN_CHANGE_REJECT: {
2682                 acceptOrRejectChanges(cur, REJECT);
2683                 break;
2684         }
2685
2686         case LFUN_THESAURUS_ENTRY: {
2687                 Language const * language = cur.getFont().language();
2688                 docstring arg = cmd.argument();
2689                 if (arg.empty()) {
2690                         arg = cur.selectionAsString(false);
2691                         // Too large. We unselect if needed and try to get
2692                         // the first word in selection or under cursor
2693                         if (arg.size() > 100 || arg.empty()) {
2694                                 if (cur.selection()) {
2695                                         DocIterator selbeg = cur.selectionBegin();
2696                                         cur.clearSelection();
2697                                         setCursorIntern(cur, selbeg.pit(), selbeg.pos());
2698                                         cur.screenUpdateFlags(Update::Force);
2699                                 }
2700                                 // Get word or selection
2701                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2702                                 arg = cur.selectionAsString(false);
2703                                 arg += " lang=" + from_ascii(language->lang());
2704                         }
2705                 } else {
2706                         string lang = cmd.getArg(1);
2707                         // This duplicates the code in GuiThesaurus::initialiseParams
2708                         if (prefixIs(lang, "lang=")) {
2709                                 language = languages.getLanguage(lang.substr(5));
2710                                 if (!language)
2711                                         language = cur.getFont().language();
2712                         }
2713                 }
2714                 string lang = language->code();
2715                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2716                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2717                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2718                                         _("The path to the thesaurus directory has not been specified.\n"
2719                                           "The thesaurus is not functional.\n"
2720                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2721                                           "instructions."));
2722                 }
2723                 bv->showDialog("thesaurus", to_utf8(arg));
2724                 break;
2725         }
2726
2727         case LFUN_SPELLING_ADD: {
2728                 Language const * language = getLanguage(cur, cmd.getArg(1));
2729                 docstring word = from_utf8(cmd.getArg(0));
2730                 if (word.empty()) {
2731                         word = cur.selectionAsString(false);
2732                         // FIXME
2733                         if (word.size() > 100 || word.empty()) {
2734                                 // Get word or selection
2735                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2736                                 word = cur.selectionAsString(false);
2737                         }
2738                 }
2739                 WordLangTuple wl(word, language);
2740                 theSpellChecker()->insert(wl);
2741                 break;
2742         }
2743
2744         case LFUN_SPELLING_ADD_LOCAL: {
2745                 Language const * language = getLanguage(cur, cmd.getArg(1));
2746                 docstring word = from_utf8(cmd.getArg(0));
2747                 if (word.empty()) {
2748                         word = cur.selectionAsString(false);
2749                         if (word.size() > 100)
2750                                 break;
2751                         if (word.empty()) {
2752                                 // Get word or selection
2753                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2754                                 word = cur.selectionAsString(false);
2755                         }
2756                 }
2757                 WordLangTuple wl(word, language);
2758                 if (!bv->buffer().params().spellignored(wl)) {
2759                         cur.recordUndoBufferParams();
2760                         bv->buffer().params().spellignore().push_back(wl);
2761                         cur.recordUndo();
2762                         // trigger re-check of whole buffer
2763                         bv->buffer().requestSpellcheck();
2764                 }
2765                 break;
2766         }
2767
2768         case LFUN_SPELLING_REMOVE_LOCAL: {
2769                 Language const * language = getLanguage(cur, cmd.getArg(1));
2770                 docstring word = from_utf8(cmd.getArg(0));
2771                 if (word.empty()) {
2772                         word = cur.selectionAsString(false);
2773                         if (word.size() > 100)
2774                                 break;
2775                         if (word.empty()) {
2776                                 // Get word or selection
2777                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2778                                 word = cur.selectionAsString(false);
2779                         }
2780                 }
2781                 WordLangTuple wl(word, language);
2782                 bool has_item = false;
2783                 vector<WordLangTuple>::const_iterator it = bv->buffer().params().spellignore().begin();
2784                 for (; it != bv->buffer().params().spellignore().end(); ++it) {
2785                         if (it->lang()->code() != wl.lang()->code())
2786                                 continue;
2787                         if (it->word() == wl.word()) {
2788                                 has_item = true;
2789                                 break;
2790                         }
2791                 }
2792                 if (has_item) {
2793                         cur.recordUndoBufferParams();
2794                         bv->buffer().params().spellignore().erase(it);
2795                         cur.recordUndo();
2796                         // trigger re-check of whole buffer
2797                         bv->buffer().requestSpellcheck();
2798                 }
2799                 break;
2800         }
2801
2802
2803         case LFUN_SPELLING_IGNORE: {
2804                 Language const * language = getLanguage(cur, cmd.getArg(1));
2805                 docstring word = from_utf8(cmd.getArg(0));
2806                 if (word.empty()) {
2807                         word = cur.selectionAsString(false);
2808                         // FIXME
2809                         if (word.size() > 100 || word.empty()) {
2810                                 // Get word or selection
2811                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2812                                 word = cur.selectionAsString(false);
2813                         }
2814                 }
2815                 WordLangTuple wl(word, language);
2816                 theSpellChecker()->accept(wl);
2817                 break;
2818         }
2819
2820         case LFUN_SPELLING_REMOVE: {
2821                 Language const * language = getLanguage(cur, cmd.getArg(1));
2822                 docstring word = from_utf8(cmd.getArg(0));
2823                 if (word.empty()) {
2824                         word = cur.selectionAsString(false);
2825                         // FIXME
2826                         if (word.size() > 100 || word.empty()) {
2827                                 // Get word or selection
2828                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2829                                 word = cur.selectionAsString(false);
2830                         }
2831                 }
2832                 WordLangTuple wl(word, language);
2833                 theSpellChecker()->remove(wl);
2834                 break;
2835         }
2836
2837         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2838                 // Given data, an encoding of the ParagraphParameters
2839                 // generated in the Paragraph dialog, this function sets
2840                 // the current paragraph, or currently selected paragraphs,
2841                 // appropriately.
2842                 // NOTE: This function overrides all existing settings.
2843                 setParagraphs(cur, cmd.argument());
2844                 cur.message(_("Paragraph layout set"));
2845                 break;
2846         }
2847
2848         case LFUN_PARAGRAPH_PARAMS: {
2849                 // Given data, an encoding of the ParagraphParameters as we'd
2850                 // find them in a LyX file, this function modifies the current paragraph,
2851                 // or currently selected paragraphs.
2852                 // NOTE: This function only modifies, and does not override, existing
2853                 // settings.
2854                 setParagraphs(cur, cmd.argument(), true);
2855                 cur.message(_("Paragraph layout set"));
2856                 break;
2857         }
2858
2859         case LFUN_ESCAPE:
2860                 if (cur.selection()) {
2861                         cur.selection(false);
2862                 } else {
2863                         cur.undispatched();
2864                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2865                         // correct, but I'm not 100% sure -- dov, 071019
2866                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2867                 }
2868                 break;
2869
2870         case LFUN_OUTLINE_UP: {
2871                 pos_type const opos = cur.pos();
2872                 outline(OutlineUp, cur, this);
2873                 setCursor(cur, cur.pit(), opos);
2874                 cur.forceBufferUpdate();
2875                 needsUpdate = true;
2876                 break;
2877         }
2878
2879         case LFUN_OUTLINE_DOWN: {
2880                 pos_type const opos = cur.pos();
2881                 outline(OutlineDown, cur, this);
2882                 setCursor(cur, cur.pit(), opos);
2883                 cur.forceBufferUpdate();
2884                 needsUpdate = true;
2885                 break;
2886         }
2887
2888         case LFUN_OUTLINE_IN:
2889                 outline(OutlineIn, cur, this);
2890                 cur.forceBufferUpdate();
2891                 needsUpdate = true;
2892                 break;
2893
2894         case LFUN_OUTLINE_OUT:
2895                 outline(OutlineOut, cur, this);
2896                 cur.forceBufferUpdate();
2897                 needsUpdate = true;
2898                 break;
2899
2900         case LFUN_SERVER_GET_STATISTICS: {
2901                 DocIterator from, to;
2902                 if (cur.selection()) {
2903                         from = cur.selectionBegin();
2904                         to = cur.selectionEnd();
2905                 } else {
2906                         from = doc_iterator_begin(cur.buffer());
2907                         to = doc_iterator_end(cur.buffer());
2908                 }
2909
2910                 cur.buffer()->updateStatistics(from, to);
2911                 string const arg0 = cmd.getArg(0);
2912                 if (arg0 == "words") {
2913                         cur.message(convert<docstring>(cur.buffer()->wordCount()));
2914                 } else if (arg0 == "chars") {
2915                         cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2916                 } else if (arg0 == "chars-space") {
2917                         cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2918                 } else {
2919                         cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2920                         + convert<docstring>(cur.buffer()->charCount(false)) + " "
2921                         + convert<docstring>(cur.buffer()->charCount(true)));
2922                 }
2923                 break;
2924         }
2925
2926         default:
2927                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2928                 cur.undispatched();
2929                 break;
2930         }
2931
2932         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2933
2934         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2935                 // Check for misspelled text
2936                 // The redraw is useful because of the painting of
2937                 // misspelled markers depends on the cursor position.
2938                 // Trigger a redraw for cursor moves inside misspelled text.
2939                 if (!cur.inTexted()) {
2940                         // move from regular text to math
2941                         needsUpdate = last_misspelled;
2942                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2943                         // move inside regular text
2944                         needsUpdate = last_misspelled
2945                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2946                 }
2947         }
2948
2949         // FIXME: The cursor flag is reset two lines below
2950         // so we need to check here if some of the LFUN did touch that.
2951         // for now only Text::erase() and Text::backspace() do that.
2952         // The plan is to verify all the LFUNs and then to remove this
2953         // singleParUpdate boolean altogether.
2954         if (cur.result().screenUpdate() & Update::Force) {
2955                 singleParUpdate = false;
2956                 needsUpdate = true;
2957         }
2958
2959         // FIXME: the following code should go in favor of fine grained
2960         // update flag treatment.
2961         if (singleParUpdate) {
2962                 // Inserting characters does not change par height in general. So, try
2963                 // to update _only_ this paragraph. BufferView will detect if a full
2964                 // metrics update is needed anyway.
2965                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2966                 return;
2967         }
2968         if (!needsUpdate
2969             && &oldTopSlice.inset() == &cur.inset()
2970             && oldTopSlice.idx() == cur.idx()
2971             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2972             && !cur.selection())
2973                 // FIXME: it would be better if we could just do this
2974                 //
2975                 //if (cur.result().update() != Update::FitCursor)
2976                 //      cur.noScreenUpdate();
2977                 //
2978                 // But some LFUNs do not set Update::FitCursor when needed, so we
2979                 // do it for all. This is not very harmfull as FitCursor will provoke
2980                 // a full redraw only if needed but still, a proper review of all LFUN
2981                 // should be done and this needsUpdate boolean can then be removed.
2982                 cur.screenUpdateFlags(Update::FitCursor);
2983         else
2984                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2985 }
2986
2987
2988 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2989                         FuncStatus & status) const
2990 {
2991         LBUFERR(this == cur.text());
2992
2993         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2994         bool enable = true;
2995         bool allow_in_passthru = false;
2996         InsetCode code = NO_CODE;
2997
2998         switch (cmd.action()) {
2999
3000         case LFUN_DEPTH_DECREMENT:
3001                 enable = changeDepthAllowed(cur, DEC_DEPTH);
3002                 break;
3003
3004         case LFUN_DEPTH_INCREMENT:
3005                 enable = changeDepthAllowed(cur, INC_DEPTH);
3006                 break;
3007
3008         case LFUN_APPENDIX:
3009                 // FIXME We really should not allow this to be put, e.g.,
3010                 // in a footnote, or in ERT. But it would make sense in a
3011                 // branch, so I'm not sure what to do.
3012                 status.setOnOff(cur.paragraph().params().startOfAppendix());
3013                 break;
3014
3015         case LFUN_DIALOG_SHOW_NEW_INSET:
3016                 if (cmd.argument() == "bibitem")
3017                         code = BIBITEM_CODE;
3018                 else if (cmd.argument() == "bibtex") {
3019                         code = BIBTEX_CODE;
3020                         // not allowed in description items
3021                         enable = !inDescriptionItem(cur);
3022                 }
3023                 else if (cmd.argument() == "box")
3024                         code = BOX_CODE;
3025                 else if (cmd.argument() == "branch")
3026                         code = BRANCH_CODE;
3027                 else if (cmd.argument() == "citation")
3028                         code = CITE_CODE;
3029                 else if (cmd.argument() == "counter")
3030                         code = COUNTER_CODE;
3031                 else if (cmd.argument() == "ert")
3032                         code = ERT_CODE;
3033                 else if (cmd.argument() == "external")
3034                         code = EXTERNAL_CODE;
3035                 else if (cmd.argument() == "float")
3036                         code = FLOAT_CODE;
3037                 else if (cmd.argument() == "graphics")
3038                         code = GRAPHICS_CODE;
3039                 else if (cmd.argument() == "href")
3040                         code = HYPERLINK_CODE;
3041                 else if (cmd.argument() == "include")
3042                         code = INCLUDE_CODE;
3043                 else if (cmd.argument() == "index")
3044                         code = INDEX_CODE;
3045                 else if (cmd.argument() == "index_print")
3046                         code = INDEX_PRINT_CODE;
3047                 else if (cmd.argument() == "listings")
3048                         code = LISTINGS_CODE;
3049                 else if (cmd.argument() == "mathspace")
3050                         code = MATH_HULL_CODE;
3051                 else if (cmd.argument() == "nomenclature")
3052                         code = NOMENCL_CODE;
3053                 else if (cmd.argument() == "nomencl_print")
3054                         code = NOMENCL_PRINT_CODE;
3055                 else if (cmd.argument() == "label")
3056                         code = LABEL_CODE;
3057                 else if (cmd.argument() == "line")
3058                         code = LINE_CODE;
3059                 else if (cmd.argument() == "note")
3060                         code = NOTE_CODE;
3061                 else if (cmd.argument() == "phantom")
3062                         code = PHANTOM_CODE;
3063                 else if (cmd.argument() == "ref")
3064                         code = REF_CODE;
3065                 else if (cmd.argument() == "space")
3066                         code = SPACE_CODE;
3067                 else if (cmd.argument() == "toc")
3068                         code = TOC_CODE;
3069                 else if (cmd.argument() == "vspace")
3070                         code = VSPACE_CODE;
3071                 else if (cmd.argument() == "wrap")
3072                         code = WRAP_CODE;
3073                 break;
3074
3075         case LFUN_ERT_INSERT:
3076                 code = ERT_CODE;
3077                 break;
3078         case LFUN_LISTING_INSERT:
3079                 code = LISTINGS_CODE;
3080                 // not allowed in description items
3081                 enable = !inDescriptionItem(cur);
3082                 break;
3083         case LFUN_FOOTNOTE_INSERT:
3084                 code = FOOT_CODE;
3085                 break;
3086         case LFUN_TABULAR_INSERT:
3087                 code = TABULAR_CODE;
3088                 break;
3089         case LFUN_TABULAR_STYLE_INSERT:
3090                 code = TABULAR_CODE;
3091                 break;
3092         case LFUN_MARGINALNOTE_INSERT:
3093                 code = MARGIN_CODE;
3094                 break;
3095         case LFUN_FLOAT_INSERT:
3096         case LFUN_FLOAT_WIDE_INSERT:
3097                 // FIXME: If there is a selection, we should check whether there
3098                 // are floats in the selection, but this has performance issues, see
3099                 // LFUN_CHANGE_ACCEPT/REJECT.
3100                 code = FLOAT_CODE;
3101                 if (inDescriptionItem(cur))
3102                         // not allowed in description items
3103                         enable = false;
3104                 else {
3105                         InsetCode const inset_code = cur.inset().lyxCode();
3106
3107                         // algorithm floats cannot be put in another float
3108                         if (to_utf8(cmd.argument()) == "algorithm") {
3109                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
3110                                 break;
3111                         }
3112
3113                         // for figures and tables: only allow in another
3114                         // float or wrap if it is of the same type and
3115                         // not a subfloat already
3116                         if(cur.inset().lyxCode() == code) {
3117                                 InsetFloat const & ins =
3118                                         static_cast<InsetFloat const &>(cur.inset());
3119                                 enable = ins.params().type == to_utf8(cmd.argument())
3120                                         && !ins.params().subfloat;
3121                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
3122                                 InsetWrap const & ins =
3123                                         static_cast<InsetWrap const &>(cur.inset());
3124                                 enable = ins.params().type == to_utf8(cmd.argument());
3125                         }
3126                 }
3127                 break;
3128         case LFUN_WRAP_INSERT:
3129                 code = WRAP_CODE;
3130                 // not allowed in description items
3131                 enable = !inDescriptionItem(cur);
3132                 break;
3133         case LFUN_FLOAT_LIST_INSERT: {
3134                 code = FLOAT_LIST_CODE;
3135                 // not allowed in description items
3136                 enable = !inDescriptionItem(cur);
3137                 if (enable) {
3138                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
3139                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
3140                         // make sure we know about such floats
3141                         if (cit == floats.end() ||
3142                                         // and that we know how to generate a list of them
3143                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
3144                                 status.setUnknown(true);
3145                                 // probably not necessary, but...
3146                                 enable = false;
3147                         }
3148                 }
3149                 break;
3150         }
3151         case LFUN_CAPTION_INSERT: {
3152                 code = CAPTION_CODE;
3153                 string arg = cmd.getArg(0);
3154                 bool varia = arg != "Unnumbered"
3155                         && cur.inset().allowsCaptionVariation(arg);
3156                 // not allowed in description items,
3157                 // and in specific insets
3158                 enable = !inDescriptionItem(cur)
3159                         && (varia || arg.empty() || arg == "Standard");
3160                 break;
3161         }
3162         case LFUN_NOTE_INSERT:
3163                 code = NOTE_CODE;
3164                 break;
3165         case LFUN_FLEX_INSERT: {
3166                 code = FLEX_CODE;
3167                 docstring s = from_utf8(cmd.getArg(0));
3168                 // Prepend "Flex:" prefix if not there
3169                 if (!prefixIs(s, from_ascii("Flex:")))
3170                         s = from_ascii("Flex:") + s;
3171                 if (!cur.buffer()->params().documentClass().hasInsetLayout(s))
3172                         enable = false;
3173                 else {
3174                         InsetLyXType ilt =
3175                                 cur.buffer()->params().documentClass().insetLayout(s).lyxtype();
3176                         if (ilt != InsetLyXType::CHARSTYLE
3177                             && ilt != InsetLyXType::CUSTOM
3178                             && ilt != InsetLyXType::STANDARD)
3179                                 enable = false;
3180                 }
3181                 break;
3182         }
3183         case LFUN_BOX_INSERT:
3184                 code = BOX_CODE;
3185                 break;
3186         case LFUN_BRANCH_INSERT:
3187                 code = BRANCH_CODE;
3188                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
3189                     && cur.buffer()->params().branchlist().empty())
3190                         enable = false;
3191                 break;
3192         case LFUN_IPA_INSERT:
3193                 code = IPA_CODE;
3194                 break;
3195         case LFUN_PHANTOM_INSERT:
3196                 code = PHANTOM_CODE;
3197                 break;
3198         case LFUN_LABEL_INSERT:
3199                 code = LABEL_CODE;
3200                 break;
3201         case LFUN_INFO_INSERT:
3202                 code = INFO_CODE;
3203                 enable = cmd.argument().empty()
3204                         || infoparams.validateArgument(cur.buffer(), cmd.argument(), true);
3205                 break;
3206         case LFUN_ARGUMENT_INSERT: {
3207                 code = ARG_CODE;
3208                 allow_in_passthru = true;
3209                 string const arg = cmd.getArg(0);
3210                 if (arg.empty()) {
3211                         enable = false;
3212                         break;
3213                 }
3214                 Layout const & lay = cur.paragraph().layout();
3215                 Layout::LaTeXArgMap args = lay.args();
3216                 Layout::LaTeXArgMap::const_iterator const lait =
3217                                 args.find(arg);
3218                 if (lait != args.end()) {
3219                         enable = true;
3220                         pit_type pit = cur.pit();
3221                         pit_type lastpit = cur.pit();
3222                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
3223                                 // In a sequence of "merged" environment layouts, we only allow
3224                                 // non-item arguments once.
3225                                 lastpit = cur.lastpit();
3226                                 // get the first paragraph in sequence with this layout
3227                                 depth_type const current_depth = cur.paragraph().params().depth();
3228                                 while (true) {
3229                                         if (pit == 0)
3230                                                 break;
3231                                         Paragraph cpar = pars_[pit - 1];
3232                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
3233                                                 --pit;
3234                                         else
3235                                                 break;
3236                                 }
3237                         }
3238                         for (; pit <= lastpit; ++pit) {
3239                                 if (pars_[pit].layout() != lay)
3240                                         break;
3241                                 for (auto const & table : pars_[pit].insetList())
3242                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
3243                                                 if (ins->name() == arg) {
3244                                                         // we have this already
3245                                                         enable = false;
3246                                                         break;
3247                                                 }
3248                         }
3249                 } else
3250                         enable = false;
3251                 break;
3252         }
3253         case LFUN_INDEX_INSERT:
3254                 code = INDEX_CODE;
3255                 break;
3256         case LFUN_INDEX_PRINT:
3257                 code = INDEX_PRINT_CODE;
3258                 // not allowed in description items
3259                 enable = !inDescriptionItem(cur);
3260                 break;
3261         case LFUN_NOMENCL_INSERT:
3262                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3263                         enable = false;
3264                         break;
3265                 }
3266                 code = NOMENCL_CODE;
3267                 break;
3268         case LFUN_NOMENCL_PRINT:
3269                 code = NOMENCL_PRINT_CODE;
3270                 // not allowed in description items
3271                 enable = !inDescriptionItem(cur);
3272                 break;
3273         case LFUN_HREF_INSERT:
3274                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3275                         enable = false;
3276                         break;
3277                 }
3278                 code = HYPERLINK_CODE;
3279                 break;
3280         case LFUN_INDEXMACRO_INSERT: {
3281                 string const arg = cmd.getArg(0);
3282                 if (arg == "sortkey")
3283                         code = INDEXMACRO_SORTKEY_CODE;
3284                 else
3285                         code = INDEXMACRO_CODE;
3286                 break;
3287         }
3288         case LFUN_IPAMACRO_INSERT: {
3289                 string const arg = cmd.getArg(0);
3290                 if (arg == "deco")
3291                         code = IPADECO_CODE;
3292                 else
3293                         code = IPACHAR_CODE;
3294                 break;
3295         }
3296         case LFUN_QUOTE_INSERT:
3297                 // always allow this, since we will inset a raw quote
3298                 // if an inset is not allowed.
3299                 allow_in_passthru = true;
3300                 break;
3301         case LFUN_SPECIALCHAR_INSERT:
3302                 code = SPECIALCHAR_CODE;
3303                 break;
3304         case LFUN_SPACE_INSERT:
3305                 // slight hack: we know this is allowed in math mode
3306                 if (cur.inTexted())
3307                         code = SPACE_CODE;
3308                 break;
3309         case LFUN_PREVIEW_INSERT:
3310                 code = PREVIEW_CODE;
3311                 break;
3312         case LFUN_SCRIPT_INSERT:
3313                 code = SCRIPT_CODE;
3314                 break;
3315
3316         case LFUN_MATH_INSERT:
3317         case LFUN_MATH_AMS_MATRIX:
3318         case LFUN_MATH_MATRIX:
3319         case LFUN_MATH_DELIM:
3320         case LFUN_MATH_BIGDELIM:
3321         case LFUN_MATH_DISPLAY:
3322         case LFUN_MATH_MODE:
3323         case LFUN_MATH_MACRO:
3324         case LFUN_MATH_SUBSCRIPT:
3325         case LFUN_MATH_SUPERSCRIPT:
3326                 code = MATH_HULL_CODE;
3327                 break;
3328
3329         case LFUN_REGEXP_MODE:
3330                 code = MATH_HULL_CODE;
3331                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3332                 break;
3333
3334         case LFUN_INSET_MODIFY:
3335                 // We need to disable this, because we may get called for a
3336                 // tabular cell via
3337                 // InsetTabular::getStatus() -> InsetText::getStatus()
3338                 // and we don't handle LFUN_INSET_MODIFY.
3339                 enable = false;
3340                 break;
3341
3342         case LFUN_FONT_EMPH:
3343                 status.setOnOff(fontinfo.emph() == FONT_ON);
3344                 enable = !cur.paragraph().isPassThru();
3345                 break;
3346
3347         case LFUN_FONT_ITAL:
3348                 status.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3349                 enable = !cur.paragraph().isPassThru();
3350                 break;
3351
3352         case LFUN_FONT_NOUN:
3353                 status.setOnOff(fontinfo.noun() == FONT_ON);
3354                 enable = !cur.paragraph().isPassThru();
3355                 break;
3356
3357         case LFUN_FONT_BOLD:
3358         case LFUN_FONT_BOLDSYMBOL:
3359                 status.setOnOff(fontinfo.series() == BOLD_SERIES);
3360                 enable = !cur.paragraph().isPassThru();
3361                 break;
3362
3363         case LFUN_FONT_SANS:
3364                 status.setOnOff(fontinfo.family() == SANS_FAMILY);
3365                 enable = !cur.paragraph().isPassThru();
3366                 break;
3367
3368         case LFUN_FONT_ROMAN:
3369                 status.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3370                 enable = !cur.paragraph().isPassThru();
3371                 break;
3372
3373         case LFUN_FONT_TYPEWRITER:
3374                 status.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3375                 enable = !cur.paragraph().isPassThru();
3376                 break;
3377
3378         case LFUN_CUT:
3379                 enable = cur.selection();
3380                 break;
3381
3382         case LFUN_PASTE: {
3383                 if (cmd.argument().empty()) {
3384                         if (theClipboard().isInternal())
3385                                 enable = cap::numberOfSelections() > 0;
3386                         else
3387                                 enable = !theClipboard().empty();
3388                         break;
3389                 }
3390
3391                 // we have an argument
3392                 string const arg = to_utf8(cmd.argument());
3393                 if (isStrUnsignedInt(arg)) {
3394                         // it's a number and therefore means the internal stack
3395                         unsigned int n = convert<unsigned int>(arg);
3396                         enable = cap::numberOfSelections() > n;
3397                         break;
3398                 }
3399
3400                 // explicit text type?
3401                 if (arg == "html") {
3402                         // Do not enable for PlainTextType, since some tidying in the
3403                         // frontend is needed for HTML, which is too unsafe for plain text.
3404                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3405                         break;
3406                 } else if (arg == "latex") {
3407                         // LaTeX is usually not available on the clipboard with
3408                         // the correct MIME type, but in plain text.
3409                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3410                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3411                         break;
3412                 }
3413
3414                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3415                 if (arg == "pdf")
3416                         type = Clipboard::PdfGraphicsType;
3417                 else if (arg == "png")
3418                         type = Clipboard::PngGraphicsType;
3419                 else if (arg == "jpeg")
3420                         type = Clipboard::JpegGraphicsType;
3421                 else if (arg == "linkback")
3422                         type = Clipboard::LinkBackGraphicsType;
3423                 else if (arg == "emf")
3424                         type = Clipboard::EmfGraphicsType;
3425                 else if (arg == "wmf")
3426                         type = Clipboard::WmfGraphicsType;
3427                 else {
3428                         // unknown argument
3429                         LYXERR0("Unrecognized graphics type: " << arg);
3430                         // we don't want to assert if the user just mistyped the LFUN
3431                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3432                         enable = false;
3433                         break;
3434                 }
3435                 enable = theClipboard().hasGraphicsContents(type);
3436                 break;
3437         }
3438
3439         case LFUN_CLIPBOARD_PASTE:
3440         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3441                 enable = !theClipboard().empty();
3442                 break;
3443
3444         case LFUN_PRIMARY_SELECTION_PASTE:
3445                 status.setUnknown(!theSelection().supported());
3446                 enable = cur.selection() || !theSelection().empty();
3447                 break;
3448
3449         case LFUN_SELECTION_PASTE:
3450                 enable = cap::selection();
3451                 break;
3452
3453         case LFUN_PARAGRAPH_MOVE_UP:
3454                 enable = cur.pit() > 0 && !cur.selection();
3455                 break;
3456
3457         case LFUN_PARAGRAPH_MOVE_DOWN:
3458                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3459                 break;
3460
3461         case LFUN_CHANGE_ACCEPT:
3462         case LFUN_CHANGE_REJECT:
3463                 if (!cur.selection())
3464                         enable = cur.paragraph().isChanged(cur.pos());
3465                 else {
3466                         // will enable if there is a change in the selection
3467                         enable = false;
3468
3469                         // cheap improvement for efficiency: using cached
3470                         // buffer variable, if there is no change in the
3471                         // document, no need to check further.
3472                         if (!cur.buffer()->areChangesPresent())
3473                                 break;
3474
3475                         for (DocIterator it = cur.selectionBegin(); ; it.forwardPar()) {
3476                                 pos_type const beg = it.pos();
3477                                 pos_type end;
3478                                 bool const in_last_par = (it.pit() == cur.selectionEnd().pit() &&
3479                                                           it.idx() == cur.selectionEnd().idx());
3480                                 if (in_last_par)
3481                                         end = cur.selectionEnd().pos();
3482                                 else
3483                                         // the +1 is needed for cases, e.g., where there is a
3484                                         // paragraph break. See #11629.
3485                                         end = it.lastpos() + 1;
3486                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3487                                         enable = true;
3488                                         break;
3489                                 }
3490                                 if (beg != end && it.paragraph().hasChangedInsets(beg, end)) {
3491                                         enable = true;
3492                                         break;
3493                                 }
3494                                 if (in_last_par)
3495                                         break;
3496                         }
3497                 }
3498                 break;
3499
3500         case LFUN_OUTLINE_UP:
3501         case LFUN_OUTLINE_DOWN:
3502         case LFUN_OUTLINE_IN:
3503         case LFUN_OUTLINE_OUT:
3504                 // FIXME: LyX is not ready for outlining within inset.
3505                 enable = isMainText()
3506                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3507                 break;
3508
3509         case LFUN_NEWLINE_INSERT:
3510                 // LaTeX restrictions (labels or empty par)
3511                 enable = !cur.paragraph().isPassThru()
3512                         && cur.pos() > cur.paragraph().beginOfBody();
3513                 break;
3514
3515         case LFUN_SEPARATOR_INSERT:
3516                 // Always enabled for now
3517                 enable = true;
3518                 break;
3519
3520         case LFUN_TAB_INSERT:
3521         case LFUN_TAB_DELETE:
3522                 enable = cur.paragraph().isPassThru();
3523                 break;
3524
3525         case LFUN_GRAPHICS_SET_GROUP: {
3526                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3527                 if (!ins)
3528                         enable = false;
3529                 else
3530                         status.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3531                 break;
3532         }
3533
3534         case LFUN_NEWPAGE_INSERT:
3535                 // not allowed in description items
3536                 code = NEWPAGE_CODE;
3537                 enable = !inDescriptionItem(cur);
3538                 break;
3539
3540         case LFUN_LANGUAGE:
3541                 enable = !cur.paragraph().isPassThru();
3542                 status.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3543                 break;
3544
3545         case LFUN_PARAGRAPH_BREAK:
3546                 enable = inset().allowMultiPar();
3547                 break;
3548
3549         case LFUN_SPELLING_ADD:
3550         case LFUN_SPELLING_ADD_LOCAL:
3551         case LFUN_SPELLING_REMOVE_LOCAL:
3552         case LFUN_SPELLING_IGNORE:
3553         case LFUN_SPELLING_REMOVE:
3554                 enable = theSpellChecker() != nullptr;
3555                 if (enable && !cmd.getArg(1).empty()) {
3556                         // validate explicitly given language
3557                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3558                         enable &= lang != nullptr;
3559                 }
3560                 break;
3561
3562         case LFUN_LAYOUT:
3563         case LFUN_LAYOUT_TOGGLE: {
3564                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3565                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3566                 docstring const layout = resolveLayout(req_layout, cur);
3567
3568                 // FIXME: make this work in multicell selection case
3569                 enable = !owner_->forcePlainLayout() && !layout.empty() && !cur.selIsMultiCell();
3570                 status.setOnOff(!owner_->forcePlainLayout() && !cur.selIsMultiCell()
3571                                 && isAlreadyLayout(layout, cur));
3572                 break;
3573         }
3574
3575         case LFUN_ENVIRONMENT_SPLIT: {
3576                 if (cmd.argument() == "outer") {
3577                         // check if we have an environment in our nesting hierarchy
3578                         bool res = false;
3579                         depth_type const current_depth = cur.paragraph().params().depth();
3580                         pit_type pit = cur.pit();
3581                         Paragraph cpar = pars_[pit];
3582                         while (true) {
3583                                 if (pit == 0 || cpar.params().depth() == 0)
3584                                         break;
3585                                 --pit;
3586                                 cpar = pars_[pit];
3587                                 if (cpar.params().depth() < current_depth)
3588                                         res = cpar.layout().isEnvironment();
3589                         }
3590                         enable = res;
3591                         break;
3592                 }
3593                 else if (cmd.argument() == "previous") {
3594                         // look if we have an environment in the previous par
3595                         pit_type pit = cur.pit();
3596                         Paragraph cpar = pars_[pit];
3597                         if (pit > 0) {
3598                                 --pit;
3599                                 cpar = pars_[pit];
3600                                 enable = cpar.layout().isEnvironment();
3601                                 break;
3602                         }
3603                         enable = false;
3604                         break;
3605                 }
3606                 else if (cur.paragraph().layout().isEnvironment()) {
3607                         enable = cmd.argument() == "before"
3608                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3609                         break;
3610                 }
3611                 enable = false;
3612                 break;
3613         }
3614
3615         case LFUN_LAYOUT_PARAGRAPH:
3616         case LFUN_PARAGRAPH_PARAMS:
3617         case LFUN_PARAGRAPH_PARAMS_APPLY:
3618         case LFUN_PARAGRAPH_UPDATE:
3619                 enable = owner_->allowParagraphCustomization();
3620                 break;
3621
3622         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3623         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3624         //  that cannot be handled by LaTeX but must be converted according
3625         //  to the definition in lib/unicodesymbols?
3626         case LFUN_ACCENT_ACUTE:
3627         case LFUN_ACCENT_BREVE:
3628         case LFUN_ACCENT_CARON:
3629         case LFUN_ACCENT_CEDILLA:
3630         case LFUN_ACCENT_CIRCLE:
3631         case LFUN_ACCENT_CIRCUMFLEX:
3632         case LFUN_ACCENT_DOT:
3633         case LFUN_ACCENT_GRAVE:
3634         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3635         case LFUN_ACCENT_MACRON:
3636         case LFUN_ACCENT_OGONEK:
3637         case LFUN_ACCENT_TIE:
3638         case LFUN_ACCENT_TILDE:
3639         case LFUN_ACCENT_PERISPOMENI:
3640         case LFUN_ACCENT_UMLAUT:
3641         case LFUN_ACCENT_UNDERBAR:
3642         case LFUN_ACCENT_UNDERDOT:
3643         case LFUN_FONT_FRAK:
3644         case LFUN_FONT_SIZE:
3645         case LFUN_FONT_STATE:
3646         case LFUN_FONT_UNDERLINE:
3647         case LFUN_FONT_STRIKEOUT:
3648         case LFUN_FONT_CROSSOUT:
3649         case LFUN_FONT_UNDERUNDERLINE:
3650         case LFUN_FONT_UNDERWAVE:
3651         case LFUN_FONT_NO_SPELLCHECK:
3652         case LFUN_TEXTSTYLE_UPDATE:
3653                 enable = !cur.paragraph().isPassThru();
3654                 break;
3655
3656         case LFUN_FONT_DEFAULT: {
3657                 Font font(inherit_font, ignore_language);
3658                 BufferParams const & bp = cur.buffer()->masterParams();
3659                 if (cur.selection()) {
3660                         enable = false;
3661                         // Check if we have a non-default font attribute
3662                         // in the selection range.
3663                         DocIterator const from = cur.selectionBegin();
3664                         DocIterator const to = cur.selectionEnd();
3665                         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
3666                                 if (!dit.inTexted()) {
3667                                         dit.forwardPos();
3668                                         continue;
3669                                 }
3670                                 Paragraph const & par = dit.paragraph();
3671                                 pos_type const pos = dit.pos();
3672                                 Font tmp = par.getFontSettings(bp, pos);
3673                                 if (tmp.fontInfo() != font.fontInfo()
3674                                     || tmp.language() != bp.language) {
3675                                         enable = true;
3676                                         break;
3677                                 }
3678                                 dit.forwardPos();
3679                         }
3680                         break;
3681                 }
3682                 // Disable if all is default already.
3683                 enable = (cur.current_font.fontInfo() != font.fontInfo()
3684                           || cur.current_font.language() != bp.language);
3685                 break;
3686         }
3687
3688         case LFUN_TEXTSTYLE_APPLY:
3689                 enable = !freeFonts.empty();
3690                 break;
3691
3692         case LFUN_WORD_DELETE_FORWARD:
3693         case LFUN_WORD_DELETE_BACKWARD:
3694         case LFUN_LINE_DELETE_FORWARD:
3695         case LFUN_WORD_FORWARD:
3696         case LFUN_WORD_BACKWARD:
3697         case LFUN_WORD_RIGHT:
3698         case LFUN_WORD_LEFT:
3699         case LFUN_CHAR_FORWARD:
3700         case LFUN_CHAR_FORWARD_SELECT:
3701         case LFUN_CHAR_BACKWARD:
3702         case LFUN_CHAR_BACKWARD_SELECT:
3703         case LFUN_CHAR_LEFT:
3704         case LFUN_CHAR_LEFT_SELECT:
3705         case LFUN_CHAR_RIGHT:
3706         case LFUN_CHAR_RIGHT_SELECT:
3707         case LFUN_UP:
3708         case LFUN_UP_SELECT:
3709         case LFUN_DOWN:
3710         case LFUN_DOWN_SELECT:
3711         case LFUN_PARAGRAPH_SELECT:
3712         case LFUN_PARAGRAPH_UP_SELECT:
3713         case LFUN_PARAGRAPH_DOWN_SELECT:
3714         case LFUN_LINE_BEGIN_SELECT:
3715         case LFUN_LINE_END_SELECT:
3716         case LFUN_WORD_FORWARD_SELECT:
3717         case LFUN_WORD_BACKWARD_SELECT:
3718         case LFUN_WORD_RIGHT_SELECT:
3719         case LFUN_WORD_LEFT_SELECT:
3720         case LFUN_WORD_SELECT:
3721         case LFUN_SECTION_SELECT:
3722         case LFUN_BUFFER_BEGIN:
3723         case LFUN_BUFFER_END:
3724         case LFUN_BUFFER_BEGIN_SELECT:
3725         case LFUN_BUFFER_END_SELECT:
3726         case LFUN_INSET_BEGIN:
3727         case LFUN_INSET_END:
3728         case LFUN_INSET_BEGIN_SELECT:
3729         case LFUN_INSET_END_SELECT:
3730         case LFUN_PARAGRAPH_UP:
3731         case LFUN_PARAGRAPH_DOWN:
3732         case LFUN_LINE_BEGIN:
3733         case LFUN_LINE_END:
3734         case LFUN_CHAR_DELETE_FORWARD:
3735         case LFUN_CHAR_DELETE_BACKWARD:
3736         case LFUN_WORD_UPCASE:
3737         case LFUN_WORD_LOWCASE:
3738         case LFUN_WORD_CAPITALIZE:
3739         case LFUN_CHARS_TRANSPOSE:
3740         case LFUN_SERVER_GET_XY:
3741         case LFUN_SERVER_SET_XY:
3742         case LFUN_SERVER_GET_LAYOUT:
3743         case LFUN_SELF_INSERT:
3744         case LFUN_UNICODE_INSERT:
3745         case LFUN_THESAURUS_ENTRY:
3746         case LFUN_ESCAPE:
3747         case LFUN_SERVER_GET_STATISTICS:
3748                 // these are handled in our dispatch()
3749                 enable = true;
3750                 break;
3751
3752         case LFUN_INSET_INSERT: {
3753                 string const type = cmd.getArg(0);
3754                 if (type == "toc") {
3755                         code = TOC_CODE;
3756                         // not allowed in description items
3757                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3758                         enable = !inDescriptionItem(cur);
3759                 } else {
3760                         enable = true;
3761                 }
3762                 break;
3763         }
3764
3765         case LFUN_SEARCH_IGNORE: {
3766                 bool const value = cmd.getArg(1) == "true";
3767                 setIgnoreFormat(cmd.getArg(0), value);
3768                 break;
3769         }
3770
3771         default:
3772                 return false;
3773         }
3774
3775         if (code != NO_CODE
3776             && (cur.empty()
3777                 || !cur.inset().insetAllowed(code)
3778                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3779                 enable = false;
3780
3781         status.setEnabled(enable);
3782         return true;
3783 }
3784
3785
3786 void Text::pasteString(Cursor & cur, docstring const & clip,
3787                 bool asParagraphs)
3788 {
3789         if (!clip.empty()) {
3790                 cur.recordUndo();
3791                 if (asParagraphs)
3792                         insertStringAsParagraphs(cur, clip, cur.current_font);
3793                 else
3794                         insertStringAsLines(cur, clip, cur.current_font);
3795         }
3796 }
3797
3798
3799 // FIXME: an item inset would make things much easier.
3800 bool Text::inDescriptionItem(Cursor const & cur) const
3801 {
3802         Paragraph const & par = cur.paragraph();
3803         pos_type const pos = cur.pos();
3804         pos_type const body_pos = par.beginOfBody();
3805
3806         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3807             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3808                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3809                 return false;
3810
3811         return (pos < body_pos
3812                 || (pos == body_pos
3813                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3814 }
3815
3816
3817 std::vector<docstring> Text::getFreeFonts() const
3818 {
3819         vector<docstring> ffList;
3820
3821         for (auto const & f : freeFonts)
3822                 ffList.push_back(f.first);
3823
3824         return ffList;
3825 }
3826
3827 } // namespace lyx