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