]> git.lyx.org Git - features.git/blob - src/Text3.cpp
Fix line breaking thinko with Qt4
[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                                 expandWordSel(bvcur);
1880                         break;
1881
1882                 case mouse_button::button2:
1883                         if (lyxrc.mouse_middlebutton_paste) {
1884                                 // Middle mouse pasting.
1885                                 bv->mouseSetCursor(cur);
1886                                 lyx::dispatch(
1887                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1888                                                     "selection-paste ; primary-selection-paste paragraph"));
1889                         }
1890                         cur.noScreenUpdate();
1891                         break;
1892
1893                 case mouse_button::button3: {
1894                         // Don't do anything if we right-click a
1895                         // selection, a context menu will popup.
1896                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1897                             && cur <= bvcur.selectionEnd()) {
1898                                 cur.noScreenUpdate();
1899                                 return;
1900                         }
1901                         if (!bv->mouseSetCursor(cur, false))
1902                                 cur.screenUpdateFlags(Update::FitCursor);
1903                         break;
1904                 }
1905
1906                 default:
1907                         break;
1908                 } // switch (cmd.button())
1909                 break;
1910         }
1911         case LFUN_MOUSE_MOTION: {
1912                 // Mouse motion with right or middle mouse do nothing for now.
1913                 if (cmd.button() != mouse_button::button1) {
1914                         cur.noScreenUpdate();
1915                         return;
1916                 }
1917                 // ignore motions deeper nested than the real anchor
1918                 Cursor & bvcur = cur.bv().cursor();
1919                 if (!bvcur.realAnchor().hasPart(cur)) {
1920                         cur.undispatched();
1921                         break;
1922                 }
1923                 CursorSlice old = bvcur.top();
1924
1925                 int const wh = bv->workHeight();
1926                 int const y = max(0, min(wh - 1, cmd.y()));
1927
1928                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1929                 cur.setTargetX(cmd.x());
1930                 // Don't allow selecting a separator inset
1931                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1932                         cur.posBackward();
1933                 if (cmd.y() >= wh)
1934                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1935                 else if (cmd.y() < 0)
1936                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1937                 // This is to allow jumping over large insets
1938                 if (cur.top() == old) {
1939                         if (cmd.y() >= wh)
1940                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1941                         else if (cmd.y() < 0)
1942                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1943                 }
1944                 // We continue with our existing selection or start a new one, so don't
1945                 // reset the anchor.
1946                 bvcur.setCursor(cur);
1947                 if (bvcur.wordSelection() && bvcur.inTexted())
1948                         expandWordSel(bvcur);
1949                 bvcur.selection(true);
1950                 bvcur.setCurrentFont();
1951                 if (cur.top() == old) {
1952                         // We didn't move one iota, so no need to update the screen.
1953                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1954                         //cur.noScreenUpdate();
1955                         return;
1956                 }
1957                 break;
1958         }
1959
1960         case LFUN_MOUSE_RELEASE:
1961                 switch (cmd.button()) {
1962                 case mouse_button::button1:
1963                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1964                         // If there is a new selection, update persistent selection;
1965                         // otherwise, single click does not clear persistent selection
1966                         // buffer.
1967                         if (cur.selection()) {
1968                                 // Finish selection. If double click,
1969                                 // cur is moved to the end of word by
1970                                 // selectWord but bvcur is current
1971                                 // mouse position.
1972                                 cur.bv().cursor().setSelection();
1973                                 // We might have removed an empty but drawn selection
1974                                 // (probably a margin)
1975                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1976                         } else
1977                                 cur.noScreenUpdate();
1978                         // FIXME: We could try to handle drag and drop of selection here.
1979                         return;
1980
1981                 case mouse_button::button2:
1982                         // Middle mouse pasting is handled at mouse press time,
1983                         // see LFUN_MOUSE_PRESS.
1984                         cur.noScreenUpdate();
1985                         return;
1986
1987                 case mouse_button::button3:
1988                         // Cursor was set at LFUN_MOUSE_PRESS time.
1989                         // FIXME: If there is a selection we could try to handle a special
1990                         // drag & drop context menu.
1991                         cur.noScreenUpdate();
1992                         return;
1993
1994                 case mouse_button::none:
1995                 case mouse_button::button4:
1996                 case mouse_button::button5:
1997                         break;
1998                 } // switch (cmd.button())
1999
2000                 break;
2001
2002         case LFUN_SELF_INSERT: {
2003                 if (cmd.argument().empty())
2004                         break;
2005
2006                 // Automatically delete the currently selected
2007                 // text and replace it with what is being
2008                 // typed in now. Depends on lyxrc settings
2009                 // "auto_region_delete", which defaults to
2010                 // true (on).
2011
2012                 if (lyxrc.auto_region_delete && cur.selection()) {
2013                         cutSelection(cur, false);
2014                         cur.setCurrentFont();
2015                 }
2016                 cur.clearSelection();
2017
2018                 for (char_type c : cmd.argument())
2019                         bv->translateAndInsert(c, this, cur);
2020
2021                 cur.resetAnchor();
2022                 moveCursor(cur, false);
2023                 cur.markNewWordPosition();
2024                 bv->bookmarkEditPosition();
2025                 break;
2026         }
2027
2028         case LFUN_HREF_INSERT: {
2029                 docstring content = cmd.argument();
2030                 if (content.empty() && cur.selection())
2031                         content = cur.selectionAsString(false);
2032
2033                 InsetCommandParams p(HYPERLINK_CODE);
2034                 if (!content.empty()){
2035                         // if it looks like a link, we'll put it as target,
2036                         // otherwise as name (bug #8792).
2037
2038                         // We can't do:
2039                         //   regex_match(to_utf8(content), matches, link_re)
2040                         // because smatch stores pointers to the substrings rather
2041                         // than making copies of them. And those pointers become
2042                         // invalid after regex_match returns, since it is then
2043                         // being given a temporary object. (Thanks to Georg for
2044                         // figuring that out.)
2045                         regex const link_re("^([a-z]+):.*");
2046                         smatch matches;
2047                         string const c = to_utf8(lowercase(content));
2048
2049                         if (c.substr(0,7) == "mailto:") {
2050                                 p["target"] = content;
2051                                 p["type"] = from_ascii("mailto:");
2052                         } else if (regex_match(c, matches, link_re)) {
2053                                 p["target"] = content;
2054                                 string protocol = matches.str(1);
2055                                 if (protocol == "file")
2056                                         p["type"] = from_ascii("file:");
2057                         } else
2058                                 p["name"] = content;
2059                 }
2060                 string const data = InsetCommand::params2string(p);
2061
2062                 // we need to have a target. if we already have one, then
2063                 // that gets used at the default for the name, too, which
2064                 // is probably what is wanted.
2065                 if (p["target"].empty()) {
2066                         bv->showDialog("href", data);
2067                 } else {
2068                         FuncRequest fr(LFUN_INSET_INSERT, data);
2069                         dispatch(cur, fr);
2070                 }
2071                 break;
2072         }
2073
2074         case LFUN_LABEL_INSERT: {
2075                 InsetCommandParams p(LABEL_CODE);
2076                 // Try to generate a valid label
2077                 p["name"] = (cmd.argument().empty()) ?
2078                         cur.getPossibleLabel() :
2079                         cmd.argument();
2080                 string const data = InsetCommand::params2string(p);
2081
2082                 if (cmd.argument().empty()) {
2083                         bv->showDialog("label", data);
2084                 } else {
2085                         FuncRequest fr(LFUN_INSET_INSERT, data);
2086                         dispatch(cur, fr);
2087                 }
2088                 break;
2089         }
2090
2091         case LFUN_INFO_INSERT: {
2092                 if (cmd.argument().empty()) {
2093                         bv->showDialog("info", cur.current_font.language()->lang());
2094                 } else {
2095                         Inset * inset;
2096                         inset = createInset(cur.buffer(), cmd);
2097                         if (!inset)
2098                                 break;
2099                         cur.recordUndo();
2100                         insertInset(cur, inset);
2101                         cur.forceBufferUpdate();
2102                         cur.posForward();
2103                 }
2104                 break;
2105         }
2106         case LFUN_CAPTION_INSERT:
2107         case LFUN_FOOTNOTE_INSERT:
2108         case LFUN_NOTE_INSERT:
2109         case LFUN_BOX_INSERT:
2110         case LFUN_BRANCH_INSERT:
2111         case LFUN_PHANTOM_INSERT:
2112         case LFUN_ERT_INSERT:
2113         case LFUN_LISTING_INSERT:
2114         case LFUN_MARGINALNOTE_INSERT:
2115         case LFUN_ARGUMENT_INSERT:
2116         case LFUN_INDEX_INSERT:
2117         case LFUN_PREVIEW_INSERT:
2118         case LFUN_SCRIPT_INSERT:
2119         case LFUN_IPA_INSERT: {
2120                 // Indexes reset font formatting (#11961)
2121                 bool const resetfont = cmd.action() == LFUN_INDEX_INSERT;
2122                 // Open the inset, and move the current selection
2123                 // inside it.
2124                 doInsertInset(cur, this, cmd, true, true, resetfont);
2125                 cur.posForward();
2126                 cur.setCurrentFont();
2127                 // Some insets are numbered, others are shown in the outline pane so
2128                 // let's update the labels and the toc backend.
2129                 cur.forceBufferUpdate();
2130                 break;
2131         }
2132
2133         case LFUN_FLEX_INSERT: {
2134                 // Open the inset, and move the current selection
2135                 // inside it.
2136                 bool const sel = cur.selection();
2137                 doInsertInset(cur, this, cmd, true, true);
2138                 // Insert auto-insert arguments
2139                 bool autoargs = false, inautoarg = false;
2140                 Layout::LaTeXArgMap args = cur.inset().getLayout().args();
2141                 for (auto const & argt : args) {
2142                         Layout::latexarg arg = argt.second;
2143                         if (!inautoarg && arg.insertonnewline && cur.pos() > 0) {
2144                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2145                                 lyx::dispatch(cmd2);
2146                         }
2147                         if (arg.autoinsert) {
2148                                 // The cursor might have been invalidated by the replaceSelection.
2149                                 cur.buffer()->changed(true);
2150                                 // If we had already inserted an arg automatically,
2151                                 // leave this now in order to insert the next one.
2152                                 if (inautoarg) {
2153                                         cur.leaveInset(cur.inset());
2154                                         cur.setCurrentFont();
2155                                         cur.posForward();
2156                                         if (arg.insertonnewline && cur.pos() > 0) {
2157                                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2158                                                 lyx::dispatch(cmd2);
2159                                         }
2160                                 }
2161                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, argt.first);
2162                                 lyx::dispatch(cmd2);
2163                                 autoargs = true;
2164                                 inautoarg = true;
2165                         }
2166                 }
2167                 if (!autoargs) {
2168                         if (sel)
2169                                 cur.leaveInset(cur.inset());
2170                         cur.posForward();
2171                 }
2172                 // Some insets are numbered, others are shown in the outline pane so
2173                 // let's update the labels and the toc backend.
2174                 cur.forceBufferUpdate();
2175                 break;
2176         }
2177
2178         case LFUN_TABULAR_INSERT: {
2179                 // if there were no arguments, just open the dialog
2180                 if (cmd.argument().empty()) {
2181                         bv->showDialog("tabularcreate");
2182                         break;
2183                 } else if (cur.buffer()->masterParams().tablestyle != "default"
2184                            || bv->buffer().params().documentClass().tablestyle() != "default") {
2185                         string tabstyle = cur.buffer()->masterParams().tablestyle;
2186                         if (tabstyle == "default")
2187                                 tabstyle = bv->buffer().params().documentClass().tablestyle();
2188                         if (!libFileSearch("tabletemplates", tabstyle + ".lyx").empty()) {
2189                                 FuncRequest fr(LFUN_TABULAR_STYLE_INSERT,
2190                                                tabstyle + " " + to_ascii(cmd.argument()));
2191                                 lyx::dispatch(fr);
2192                                 break;
2193                         } else
2194                                 // Unknown style. Report and fall back to default.
2195                                 cur.errorMessage(from_utf8(N_("Table Style ")) + from_utf8(tabstyle) +
2196                                                      from_utf8(N_(" not known")));
2197                 }
2198                 if (doInsertInset(cur, this, cmd, false, true))
2199                         cur.posForward();
2200                 break;
2201         }
2202
2203         case LFUN_TABULAR_STYLE_INSERT: {
2204                 string const style = cmd.getArg(0);
2205                 string const rows = cmd.getArg(1);
2206                 string const cols = cmd.getArg(2);
2207                 if (cols.empty() || !isStrInt(cols)
2208                     || rows.empty() || !isStrInt(rows))
2209                         break;
2210                 int const r = convert<int>(rows);
2211                 int const c = convert<int>(cols);
2212
2213                 string suffix;
2214                 if (r == 1)
2215                         suffix = "_1x1";
2216                 else if (r == 2)
2217                         suffix = "_1x2";
2218                 FileName const tabstyle = libFileSearch("tabletemplates",
2219                                                         style + suffix + ".lyx", "lyx");
2220                 if (tabstyle.empty())
2221                             break;
2222                 UndoGroupHelper ugh(cur.buffer());
2223                 cur.recordUndo();
2224                 FuncRequest cmd2(LFUN_FILE_INSERT, tabstyle.absFileName() + " ignorelang");
2225                 lyx::dispatch(cmd2);
2226                 // go into table
2227                 cur.backwardPos();
2228                 if (r > 2) {
2229                         // move one cell up to middle cell
2230                         cur.up();
2231                         // add the missing rows
2232                         int const addrows = r - 3;
2233                         for (int i = 0 ; i < addrows ; ++i) {
2234                                 FuncRequest fr(LFUN_TABULAR_FEATURE, "append-row");
2235                                 lyx::dispatch(fr);
2236                         }
2237                 }
2238                 // add the missing columns
2239                 int const addcols = c - 1;
2240                 for (int i = 0 ; i < addcols ; ++i) {
2241                         FuncRequest fr(LFUN_TABULAR_FEATURE, "append-column");
2242                         lyx::dispatch(fr);
2243                 }
2244                 if (r > 1)
2245                         // go to first cell
2246                         cur.up();
2247                 break;
2248         }
2249
2250         case LFUN_FLOAT_INSERT:
2251         case LFUN_FLOAT_WIDE_INSERT:
2252         case LFUN_WRAP_INSERT: {
2253                 // will some content be moved into the inset?
2254                 bool const content = cur.selection();
2255                 // does the content consist of multiple paragraphs?
2256                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2257
2258                 doInsertInset(cur, this, cmd, true, true);
2259                 cur.posForward();
2260
2261                 // If some single-par content is moved into the inset,
2262                 // doInsertInset puts the cursor outside the inset.
2263                 // To insert the caption we put it back into the inset.
2264                 // FIXME cleanup doInsertInset to avoid such dances!
2265                 if (content && singlepar)
2266                         cur.backwardPos();
2267
2268                 ParagraphList & pars = cur.text()->paragraphs();
2269
2270                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2271
2272                 // add a separate paragraph for the caption inset
2273                 pars.push_back(Paragraph());
2274                 pars.back().setInsetOwner(&cur.text()->inset());
2275                 pars.back().setPlainOrDefaultLayout(tclass);
2276                 int cap_pit = pars.size() - 1;
2277
2278                 // if an empty inset was created, we create an additional empty
2279                 // paragraph at the bottom so that the user can choose where to put
2280                 // the graphics (or table).
2281                 if (!content) {
2282                         pars.push_back(Paragraph());
2283                         pars.back().setInsetOwner(&cur.text()->inset());
2284                         pars.back().setPlainOrDefaultLayout(tclass);
2285                 }
2286
2287                 // reposition the cursor to the caption
2288                 cur.pit() = cap_pit;
2289                 cur.pos() = 0;
2290                 // FIXME: This Text/Cursor dispatch handling is a mess!
2291                 // We cannot use Cursor::dispatch here it needs access to up to
2292                 // date metrics.
2293                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2294                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2295                 cur.forceBufferUpdate();
2296                 cur.screenUpdateFlags(Update::Force);
2297                 // FIXME: When leaving the Float (or Wrap) inset we should
2298                 // delete any empty paragraph left above or below the
2299                 // caption.
2300                 break;
2301         }
2302
2303         case LFUN_NOMENCL_INSERT: {
2304                 InsetCommandParams p(NOMENCL_CODE);
2305                 if (cmd.argument().empty()) {
2306                         p["symbol"] =
2307                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2308                         cur.clearSelection();
2309                 } else
2310                         p["symbol"] = cmd.argument();
2311                 string const data = InsetCommand::params2string(p);
2312                 bv->showDialog("nomenclature", data);
2313                 break;
2314         }
2315
2316         case LFUN_INDEX_PRINT: {
2317                 InsetCommandParams p(INDEX_PRINT_CODE);
2318                 if (cmd.argument().empty())
2319                         p["type"] = from_ascii("idx");
2320                 else
2321                         p["type"] = cmd.argument();
2322                 string const data = InsetCommand::params2string(p);
2323                 FuncRequest fr(LFUN_INSET_INSERT, data);
2324                 dispatch(cur, fr);
2325                 break;
2326         }
2327
2328         case LFUN_NOMENCL_PRINT:
2329         case LFUN_NEWPAGE_INSERT:
2330                 // do nothing fancy
2331                 doInsertInset(cur, this, cmd, false, false);
2332                 cur.posForward();
2333                 break;
2334
2335         case LFUN_SEPARATOR_INSERT: {
2336                 doInsertInset(cur, this, cmd, false, false);
2337                 cur.posForward();
2338                 // remove a following space
2339                 Paragraph & par = cur.paragraph();
2340                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2341                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2342                 break;
2343         }
2344
2345         case LFUN_DEPTH_DECREMENT:
2346                 changeDepth(cur, DEC_DEPTH);
2347                 break;
2348
2349         case LFUN_DEPTH_INCREMENT:
2350                 changeDepth(cur, INC_DEPTH);
2351                 break;
2352
2353         case LFUN_REGEXP_MODE:
2354                 regexpDispatch(cur, cmd);
2355                 break;
2356
2357         case LFUN_MATH_MODE: {
2358                 if (cmd.argument() == "on" || cmd.argument() == "") {
2359                         // don't pass "on" as argument
2360                         // (it would appear literally in the first cell)
2361                         docstring sel = cur.selectionAsString(false);
2362                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2363                         // create a macro template if we see "\\newcommand" somewhere, and
2364                         // an ordinary formula otherwise
2365                         if (!sel.empty()
2366                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2367                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2368                                         || sel.find(from_ascii("\\def")) != string::npos)
2369                                 && macro->fromString(sel)) {
2370                                 cur.recordUndo();
2371                                 replaceSelection(cur);
2372                                 cur.insert(macro);
2373                         } else {
2374                                 // no meaningful macro template was found
2375                                 delete macro;
2376                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2377                         }
2378                 } else
2379                         // The argument is meaningful
2380                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2381                         // has a different meaning in math mode
2382                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2383                 break;
2384         }
2385
2386         case LFUN_MATH_MACRO:
2387                 if (cmd.argument().empty())
2388                         cur.errorMessage(from_utf8(N_("Missing argument")));
2389                 else {
2390                         cur.recordUndo();
2391                         string s = to_utf8(cmd.argument());
2392                         string const s1 = token(s, ' ', 1);
2393                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2394                         string const s2 = token(s, ' ', 2);
2395                         MacroType type = MacroTypeNewcommand;
2396                         if (s2 == "def")
2397                                 type = MacroTypeDef;
2398                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2399                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2400                         inset->setBuffer(bv->buffer());
2401                         insertInset(cur, inset);
2402
2403                         // enter macro inset and select the name
2404                         cur.push(*inset);
2405                         cur.top().pos() = cur.top().lastpos();
2406                         cur.resetAnchor();
2407                         cur.selection(true);
2408                         cur.top().pos() = 0;
2409                 }
2410                 break;
2411
2412         case LFUN_MATH_DISPLAY:
2413         case LFUN_MATH_SUBSCRIPT:
2414         case LFUN_MATH_SUPERSCRIPT:
2415         case LFUN_MATH_INSERT:
2416         case LFUN_MATH_AMS_MATRIX:
2417         case LFUN_MATH_MATRIX:
2418         case LFUN_MATH_DELIM:
2419         case LFUN_MATH_BIGDELIM:
2420                 mathDispatch(cur, cmd);
2421                 break;
2422
2423         case LFUN_FONT_EMPH: {
2424                 Font font(ignore_font, ignore_language);
2425                 font.fontInfo().setEmph(FONT_TOGGLE);
2426                 toggleAndShow(cur, this, font);
2427                 break;
2428         }
2429
2430         case LFUN_FONT_ITAL: {
2431                 Font font(ignore_font, ignore_language);
2432                 font.fontInfo().setShape(ITALIC_SHAPE);
2433                 toggleAndShow(cur, this, font);
2434                 break;
2435         }
2436
2437         case LFUN_FONT_BOLD:
2438         case LFUN_FONT_BOLDSYMBOL: {
2439                 Font font(ignore_font, ignore_language);
2440                 font.fontInfo().setSeries(BOLD_SERIES);
2441                 toggleAndShow(cur, this, font);
2442                 break;
2443         }
2444
2445         case LFUN_FONT_NOUN: {
2446                 Font font(ignore_font, ignore_language);
2447                 font.fontInfo().setNoun(FONT_TOGGLE);
2448                 toggleAndShow(cur, this, font);
2449                 break;
2450         }
2451
2452         case LFUN_FONT_TYPEWRITER: {
2453                 Font font(ignore_font, ignore_language);
2454                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2455                 toggleAndShow(cur, this, font);
2456                 break;
2457         }
2458
2459         case LFUN_FONT_SANS: {
2460                 Font font(ignore_font, ignore_language);
2461                 font.fontInfo().setFamily(SANS_FAMILY);
2462                 toggleAndShow(cur, this, font);
2463                 break;
2464         }
2465
2466         case LFUN_FONT_ROMAN: {
2467                 Font font(ignore_font, ignore_language);
2468                 font.fontInfo().setFamily(ROMAN_FAMILY);
2469                 toggleAndShow(cur, this, font);
2470                 break;
2471         }
2472
2473         case LFUN_FONT_DEFAULT: {
2474                 Font font(inherit_font, ignore_language);
2475                 toggleAndShow(cur, this, font);
2476                 break;
2477         }
2478
2479         case LFUN_FONT_STRIKEOUT: {
2480                 Font font(ignore_font, ignore_language);
2481                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2482                 toggleAndShow(cur, this, font);
2483                 break;
2484         }
2485
2486         case LFUN_FONT_CROSSOUT: {
2487                 Font font(ignore_font, ignore_language);
2488                 font.fontInfo().setXout(FONT_TOGGLE);
2489                 toggleAndShow(cur, this, font);
2490                 break;
2491         }
2492
2493         case LFUN_FONT_UNDERUNDERLINE: {
2494                 Font font(ignore_font, ignore_language);
2495                 font.fontInfo().setUuline(FONT_TOGGLE);
2496                 toggleAndShow(cur, this, font);
2497                 break;
2498         }
2499
2500         case LFUN_FONT_UNDERWAVE: {
2501                 Font font(ignore_font, ignore_language);
2502                 font.fontInfo().setUwave(FONT_TOGGLE);
2503                 toggleAndShow(cur, this, font);
2504                 break;
2505         }
2506
2507         case LFUN_FONT_UNDERLINE: {
2508                 Font font(ignore_font, ignore_language);
2509                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2510                 toggleAndShow(cur, this, font);
2511                 break;
2512         }
2513
2514         case LFUN_FONT_NO_SPELLCHECK: {
2515                 Font font(ignore_font, ignore_language);
2516                 font.fontInfo().setNoSpellcheck(FONT_TOGGLE);
2517                 toggleAndShow(cur, this, font);
2518                 break;
2519         }
2520
2521         case LFUN_FONT_SIZE: {
2522                 Font font(ignore_font, ignore_language);
2523                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2524                 toggleAndShow(cur, this, font);
2525                 break;
2526         }
2527
2528         case LFUN_LANGUAGE: {
2529                 string const lang_arg = cmd.getArg(0);
2530                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2531                 Language const * lang =
2532                         reset ? reset_language
2533                               : languages.getLanguage(lang_arg);
2534                 // we allow reset_language, which is 0, but only if it
2535                 // was requested via empty or "reset" arg.
2536                 if (!lang && !reset)
2537                         break;
2538                 bool const toggle = (cmd.getArg(1) != "set");
2539                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2540                 Font font(ignore_font, lang);
2541                 toggleAndShow(cur, this, font, toggle);
2542                 break;
2543         }
2544
2545         case LFUN_TEXTSTYLE_APPLY: {
2546                 unsigned int num = 0;
2547                 string const arg = to_utf8(cmd.argument());
2548                 // Argument?
2549                 if (!arg.empty()) {
2550                         if (isStrUnsignedInt(arg)) {
2551                                 num = convert<uint>(arg);
2552                                 if (num >= freeFonts.size()) {
2553                                         cur.message(_("Invalid argument (number exceeds stack size)!"));
2554                                         break;
2555                                 }
2556                         } else {
2557                                 cur.message(_("Invalid argument (must be a non-negative number)!"));
2558                                 break;
2559                         }
2560                 }
2561                 toggleAndShow(cur, this, freeFonts[num].second, toggleall);
2562                 cur.message(bformat(_("Text properties applied: %1$s"), freeFonts[num].first));
2563                 break;
2564         }
2565
2566         // Set the freefont using the contents of \param data dispatched from
2567         // the frontends and apply it at the current cursor location.
2568         case LFUN_TEXTSTYLE_UPDATE: {
2569                 Font font(ignore_font, ignore_language);
2570                 bool toggle;
2571                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2572                         docstring const props = font.stateText(&bv->buffer().params(), true);
2573                         freeFonts.push(make_pair(props, font));
2574                         toggleall = toggle;
2575                         toggleAndShow(cur, this, font, toggleall);
2576                         cur.message(bformat(_("Text properties applied: %1$s"), props));
2577                 } else
2578                         LYXERR0("Invalid argument of textstyle-update");
2579                 break;
2580         }
2581
2582         case LFUN_FINISHED_LEFT:
2583                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2584                 // We're leaving an inset, going left. If the inset is LTR, we're
2585                 // leaving from the front, so we should not move (remain at --- but
2586                 // not in --- the inset). If the inset is RTL, move left, without
2587                 // entering the inset itself; i.e., move to after the inset.
2588                 if (cur.paragraph().getFontSettings(
2589                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2590                         cursorVisLeft(cur, true);
2591                 break;
2592
2593         case LFUN_FINISHED_RIGHT:
2594                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2595                 // We're leaving an inset, going right. If the inset is RTL, we're
2596                 // leaving from the front, so we should not move (remain at --- but
2597                 // not in --- the inset). If the inset is LTR, move right, without
2598                 // entering the inset itself; i.e., move to after the inset.
2599                 if (!cur.paragraph().getFontSettings(
2600                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2601                         cursorVisRight(cur, true);
2602                 break;
2603
2604         case LFUN_FINISHED_BACKWARD:
2605                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2606                 cur.setCurrentFont();
2607                 break;
2608
2609         case LFUN_FINISHED_FORWARD:
2610                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2611                 ++cur.pos();
2612                 cur.setCurrentFont();
2613                 break;
2614
2615         case LFUN_LAYOUT_PARAGRAPH: {
2616                 string data;
2617                 params2string(cur.paragraph(), data);
2618                 data = "show\n" + data;
2619                 bv->showDialog("paragraph", data);
2620                 break;
2621         }
2622
2623         case LFUN_PARAGRAPH_UPDATE: {
2624                 string data;
2625                 params2string(cur.paragraph(), data);
2626
2627                 // Will the paragraph accept changes from the dialog?
2628                 bool const accept =
2629                         cur.inset().allowParagraphCustomization(cur.idx());
2630
2631                 data = "update " + convert<string>(accept) + '\n' + data;
2632                 bv->updateDialog("paragraph", data);
2633                 break;
2634         }
2635
2636         case LFUN_ACCENT_UMLAUT:
2637         case LFUN_ACCENT_CIRCUMFLEX:
2638         case LFUN_ACCENT_GRAVE:
2639         case LFUN_ACCENT_ACUTE:
2640         case LFUN_ACCENT_TILDE:
2641         case LFUN_ACCENT_PERISPOMENI:
2642         case LFUN_ACCENT_CEDILLA:
2643         case LFUN_ACCENT_MACRON:
2644         case LFUN_ACCENT_DOT:
2645         case LFUN_ACCENT_UNDERDOT:
2646         case LFUN_ACCENT_UNDERBAR:
2647         case LFUN_ACCENT_CARON:
2648         case LFUN_ACCENT_BREVE:
2649         case LFUN_ACCENT_TIE:
2650         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2651         case LFUN_ACCENT_CIRCLE:
2652         case LFUN_ACCENT_OGONEK:
2653                 theApp()->handleKeyFunc(cmd.action());
2654                 if (!cmd.argument().empty())
2655                         // FIXME: Are all these characters encoded in one byte in utf8?
2656                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2657                 cur.screenUpdateFlags(Update::FitCursor);
2658                 break;
2659
2660         case LFUN_FLOAT_LIST_INSERT: {
2661                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2662                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2663                         cur.recordUndo();
2664                         if (cur.selection())
2665                                 cutSelection(cur, false);
2666                         breakParagraph(cur);
2667
2668                         if (cur.lastpos() != 0) {
2669                                 cursorBackward(cur);
2670                                 breakParagraph(cur);
2671                         }
2672
2673                         docstring const laystr = cur.inset().usePlainLayout() ?
2674                                 tclass.plainLayoutName() :
2675                                 tclass.defaultLayoutName();
2676                         setLayout(cur, laystr);
2677                         ParagraphParameters p;
2678                         // FIXME If this call were replaced with one to clearParagraphParams(),
2679                         // then we could get rid of this method altogether.
2680                         setParagraphs(cur, p);
2681                         // FIXME This should be simplified when InsetFloatList takes a
2682                         // Buffer in its constructor.
2683                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2684                         ifl->setBuffer(bv->buffer());
2685                         insertInset(cur, ifl);
2686                         cur.posForward();
2687                 } else {
2688                         lyxerr << "Non-existent float type: "
2689                                << to_utf8(cmd.argument()) << endl;
2690                 }
2691                 break;
2692         }
2693
2694         case LFUN_CHANGE_ACCEPT: {
2695                 acceptOrRejectChanges(cur, ACCEPT);
2696                 break;
2697         }
2698
2699         case LFUN_CHANGE_REJECT: {
2700                 acceptOrRejectChanges(cur, REJECT);
2701                 break;
2702         }
2703
2704         case LFUN_THESAURUS_ENTRY: {
2705                 Language const * language = cur.getFont().language();
2706                 docstring arg = cmd.argument();
2707                 if (arg.empty()) {
2708                         arg = cur.selectionAsString(false);
2709                         // Too large. We unselect if needed and try to get
2710                         // the first word in selection or under cursor
2711                         if (arg.size() > 100 || arg.empty()) {
2712                                 if (cur.selection()) {
2713                                         DocIterator selbeg = cur.selectionBegin();
2714                                         cur.clearSelection();
2715                                         setCursorIntern(cur, selbeg.pit(), selbeg.pos());
2716                                         cur.screenUpdateFlags(Update::Force);
2717                                 }
2718                                 // Get word or selection
2719                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2720                                 arg = cur.selectionAsString(false);
2721                                 arg += " lang=" + from_ascii(language->lang());
2722                         }
2723                 } else {
2724                         string lang = cmd.getArg(1);
2725                         // This duplicates the code in GuiThesaurus::initialiseParams
2726                         if (prefixIs(lang, "lang=")) {
2727                                 language = languages.getLanguage(lang.substr(5));
2728                                 if (!language)
2729                                         language = cur.getFont().language();
2730                         }
2731                 }
2732                 string lang = language->code();
2733                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2734                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2735                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2736                                         _("The path to the thesaurus directory has not been specified.\n"
2737                                           "The thesaurus is not functional.\n"
2738                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2739                                           "instructions."));
2740                 }
2741                 bv->showDialog("thesaurus", to_utf8(arg));
2742                 break;
2743         }
2744
2745         case LFUN_SPELLING_ADD: {
2746                 Language const * language = getLanguage(cur, cmd.getArg(1));
2747                 docstring word = from_utf8(cmd.getArg(0));
2748                 if (word.empty()) {
2749                         word = cur.selectionAsString(false);
2750                         // FIXME
2751                         if (word.size() > 100 || word.empty()) {
2752                                 // Get word or selection
2753                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2754                                 word = cur.selectionAsString(false);
2755                         }
2756                 }
2757                 WordLangTuple wl(word, language);
2758                 theSpellChecker()->insert(wl);
2759                 break;
2760         }
2761
2762         case LFUN_SPELLING_ADD_LOCAL: {
2763                 Language const * language = getLanguage(cur, cmd.getArg(1));
2764                 docstring word = from_utf8(cmd.getArg(0));
2765                 if (word.empty()) {
2766                         word = cur.selectionAsString(false);
2767                         if (word.size() > 100)
2768                                 break;
2769                         if (word.empty()) {
2770                                 // Get word or selection
2771                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2772                                 word = cur.selectionAsString(false);
2773                         }
2774                 }
2775                 WordLangTuple wl(word, language);
2776                 if (!bv->buffer().params().spellignored(wl)) {
2777                         cur.recordUndoBufferParams();
2778                         bv->buffer().params().spellignore().push_back(wl);
2779                         cur.recordUndo();
2780                         // trigger re-check of whole buffer
2781                         bv->buffer().requestSpellcheck();
2782                 }
2783                 break;
2784         }
2785
2786         case LFUN_SPELLING_REMOVE_LOCAL: {
2787                 Language const * language = getLanguage(cur, cmd.getArg(1));
2788                 docstring word = from_utf8(cmd.getArg(0));
2789                 if (word.empty()) {
2790                         word = cur.selectionAsString(false);
2791                         if (word.size() > 100)
2792                                 break;
2793                         if (word.empty()) {
2794                                 // Get word or selection
2795                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2796                                 word = cur.selectionAsString(false);
2797                         }
2798                 }
2799                 WordLangTuple wl(word, language);
2800                 bool has_item = false;
2801                 vector<WordLangTuple>::const_iterator it = bv->buffer().params().spellignore().begin();
2802                 for (; it != bv->buffer().params().spellignore().end(); ++it) {
2803                         if (it->lang()->code() != wl.lang()->code())
2804                                 continue;
2805                         if (it->word() == wl.word()) {
2806                                 has_item = true;
2807                                 break;
2808                         }
2809                 }
2810                 if (has_item) {
2811                         cur.recordUndoBufferParams();
2812                         bv->buffer().params().spellignore().erase(it);
2813                         cur.recordUndo();
2814                         // trigger re-check of whole buffer
2815                         bv->buffer().requestSpellcheck();
2816                 }
2817                 break;
2818         }
2819
2820
2821         case LFUN_SPELLING_IGNORE: {
2822                 Language const * language = getLanguage(cur, cmd.getArg(1));
2823                 docstring word = from_utf8(cmd.getArg(0));
2824                 if (word.empty()) {
2825                         word = cur.selectionAsString(false);
2826                         // FIXME
2827                         if (word.size() > 100 || word.empty()) {
2828                                 // Get word or selection
2829                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2830                                 word = cur.selectionAsString(false);
2831                         }
2832                 }
2833                 WordLangTuple wl(word, language);
2834                 theSpellChecker()->accept(wl);
2835                 break;
2836         }
2837
2838         case LFUN_SPELLING_REMOVE: {
2839                 Language const * language = getLanguage(cur, cmd.getArg(1));
2840                 docstring word = from_utf8(cmd.getArg(0));
2841                 if (word.empty()) {
2842                         word = cur.selectionAsString(false);
2843                         // FIXME
2844                         if (word.size() > 100 || word.empty()) {
2845                                 // Get word or selection
2846                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2847                                 word = cur.selectionAsString(false);
2848                         }
2849                 }
2850                 WordLangTuple wl(word, language);
2851                 theSpellChecker()->remove(wl);
2852                 break;
2853         }
2854
2855         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2856                 // Given data, an encoding of the ParagraphParameters
2857                 // generated in the Paragraph dialog, this function sets
2858                 // the current paragraph, or currently selected paragraphs,
2859                 // appropriately.
2860                 // NOTE: This function overrides all existing settings.
2861                 setParagraphs(cur, cmd.argument());
2862                 cur.message(_("Paragraph layout set"));
2863                 break;
2864         }
2865
2866         case LFUN_PARAGRAPH_PARAMS: {
2867                 // Given data, an encoding of the ParagraphParameters as we'd
2868                 // find them in a LyX file, this function modifies the current paragraph,
2869                 // or currently selected paragraphs.
2870                 // NOTE: This function only modifies, and does not override, existing
2871                 // settings.
2872                 setParagraphs(cur, cmd.argument(), true);
2873                 cur.message(_("Paragraph layout set"));
2874                 break;
2875         }
2876
2877         case LFUN_ESCAPE:
2878                 if (cur.selection()) {
2879                         cur.selection(false);
2880                 } else {
2881                         cur.undispatched();
2882                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2883                         // correct, but I'm not 100% sure -- dov, 071019
2884                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2885                 }
2886                 break;
2887
2888         case LFUN_OUTLINE_UP: {
2889                 pos_type const opos = cur.pos();
2890                 outline(OutlineUp, cur, this);
2891                 setCursor(cur, cur.pit(), opos);
2892                 cur.forceBufferUpdate();
2893                 needsUpdate = true;
2894                 break;
2895         }
2896
2897         case LFUN_OUTLINE_DOWN: {
2898                 pos_type const opos = cur.pos();
2899                 outline(OutlineDown, cur, this);
2900                 setCursor(cur, cur.pit(), opos);
2901                 cur.forceBufferUpdate();
2902                 needsUpdate = true;
2903                 break;
2904         }
2905
2906         case LFUN_OUTLINE_IN:
2907                 outline(OutlineIn, cur, this);
2908                 cur.forceBufferUpdate();
2909                 needsUpdate = true;
2910                 break;
2911
2912         case LFUN_OUTLINE_OUT:
2913                 outline(OutlineOut, cur, this);
2914                 cur.forceBufferUpdate();
2915                 needsUpdate = true;
2916                 break;
2917
2918         case LFUN_SERVER_GET_STATISTICS: {
2919                 DocIterator from, to;
2920                 if (cur.selection()) {
2921                         from = cur.selectionBegin();
2922                         to = cur.selectionEnd();
2923                 } else {
2924                         from = doc_iterator_begin(cur.buffer());
2925                         to = doc_iterator_end(cur.buffer());
2926                 }
2927
2928                 cur.buffer()->updateStatistics(from, to);
2929                 string const arg0 = cmd.getArg(0);
2930                 if (arg0 == "words") {
2931                         cur.message(convert<docstring>(cur.buffer()->wordCount()));
2932                 } else if (arg0 == "chars") {
2933                         cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2934                 } else if (arg0 == "chars-space") {
2935                         cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2936                 } else {
2937                         cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2938                         + convert<docstring>(cur.buffer()->charCount(false)) + " "
2939                         + convert<docstring>(cur.buffer()->charCount(true)));
2940                 }
2941                 break;
2942         }
2943
2944         default:
2945                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2946                 cur.undispatched();
2947                 break;
2948         }
2949
2950         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2951
2952         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2953                 // Check for misspelled text
2954                 // The redraw is useful because of the painting of
2955                 // misspelled markers depends on the cursor position.
2956                 // Trigger a redraw for cursor moves inside misspelled text.
2957                 if (!cur.inTexted()) {
2958                         // move from regular text to math
2959                         needsUpdate = last_misspelled;
2960                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2961                         // move inside regular text
2962                         needsUpdate = last_misspelled
2963                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2964                 }
2965         }
2966
2967         // FIXME: The cursor flag is reset two lines below
2968         // so we need to check here if some of the LFUN did touch that.
2969         // for now only Text::erase() and Text::backspace() do that.
2970         // The plan is to verify all the LFUNs and then to remove this
2971         // singleParUpdate boolean altogether.
2972         if (cur.result().screenUpdate() & Update::Force) {
2973                 singleParUpdate = false;
2974                 needsUpdate = true;
2975         }
2976
2977         // FIXME: the following code should go in favor of fine grained
2978         // update flag treatment.
2979         if (singleParUpdate) {
2980                 // Inserting characters does not change par height in general. So, try
2981                 // to update _only_ this paragraph. BufferView will detect if a full
2982                 // metrics update is needed anyway.
2983                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2984                 return;
2985         }
2986         if (!needsUpdate
2987             && &oldTopSlice.inset() == &cur.inset()
2988             && oldTopSlice.idx() == cur.idx()
2989             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2990             && !cur.selection())
2991                 // FIXME: it would be better if we could just do this
2992                 //
2993                 //if (cur.result().update() != Update::FitCursor)
2994                 //      cur.noScreenUpdate();
2995                 //
2996                 // But some LFUNs do not set Update::FitCursor when needed, so we
2997                 // do it for all. This is not very harmfull as FitCursor will provoke
2998                 // a full redraw only if needed but still, a proper review of all LFUN
2999                 // should be done and this needsUpdate boolean can then be removed.
3000                 cur.screenUpdateFlags(Update::FitCursor);
3001         else
3002                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
3003 }
3004
3005
3006 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
3007                         FuncStatus & status) const
3008 {
3009         LBUFERR(this == cur.text());
3010
3011         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
3012         bool enable = true;
3013         bool allow_in_passthru = false;
3014         InsetCode code = NO_CODE;
3015
3016         switch (cmd.action()) {
3017
3018         case LFUN_DEPTH_DECREMENT:
3019                 enable = changeDepthAllowed(cur, DEC_DEPTH);
3020                 break;
3021
3022         case LFUN_DEPTH_INCREMENT:
3023                 enable = changeDepthAllowed(cur, INC_DEPTH);
3024                 break;
3025
3026         case LFUN_APPENDIX:
3027                 // FIXME We really should not allow this to be put, e.g.,
3028                 // in a footnote, or in ERT. But it would make sense in a
3029                 // branch, so I'm not sure what to do.
3030                 status.setOnOff(cur.paragraph().params().startOfAppendix());
3031                 break;
3032
3033         case LFUN_DIALOG_SHOW_NEW_INSET:
3034                 if (cmd.argument() == "bibitem")
3035                         code = BIBITEM_CODE;
3036                 else if (cmd.argument() == "bibtex") {
3037                         code = BIBTEX_CODE;
3038                         // not allowed in description items
3039                         enable = !inDescriptionItem(cur);
3040                 }
3041                 else if (cmd.argument() == "box")
3042                         code = BOX_CODE;
3043                 else if (cmd.argument() == "branch")
3044                         code = BRANCH_CODE;
3045                 else if (cmd.argument() == "citation")
3046                         code = CITE_CODE;
3047                 else if (cmd.argument() == "counter")
3048                         code = COUNTER_CODE;
3049                 else if (cmd.argument() == "ert")
3050                         code = ERT_CODE;
3051                 else if (cmd.argument() == "external")
3052                         code = EXTERNAL_CODE;
3053                 else if (cmd.argument() == "float")
3054                         code = FLOAT_CODE;
3055                 else if (cmd.argument() == "graphics")
3056                         code = GRAPHICS_CODE;
3057                 else if (cmd.argument() == "href")
3058                         code = HYPERLINK_CODE;
3059                 else if (cmd.argument() == "include")
3060                         code = INCLUDE_CODE;
3061                 else if (cmd.argument() == "index")
3062                         code = INDEX_CODE;
3063                 else if (cmd.argument() == "index_print")
3064                         code = INDEX_PRINT_CODE;
3065                 else if (cmd.argument() == "listings")
3066                         code = LISTINGS_CODE;
3067                 else if (cmd.argument() == "mathspace")
3068                         code = MATH_HULL_CODE;
3069                 else if (cmd.argument() == "nomenclature")
3070                         code = NOMENCL_CODE;
3071                 else if (cmd.argument() == "nomencl_print")
3072                         code = NOMENCL_PRINT_CODE;
3073                 else if (cmd.argument() == "label")
3074                         code = LABEL_CODE;
3075                 else if (cmd.argument() == "line")
3076                         code = LINE_CODE;
3077                 else if (cmd.argument() == "note")
3078                         code = NOTE_CODE;
3079                 else if (cmd.argument() == "phantom")
3080                         code = PHANTOM_CODE;
3081                 else if (cmd.argument() == "ref")
3082                         code = REF_CODE;
3083                 else if (cmd.argument() == "space")
3084                         code = SPACE_CODE;
3085                 else if (cmd.argument() == "toc")
3086                         code = TOC_CODE;
3087                 else if (cmd.argument() == "vspace")
3088                         code = VSPACE_CODE;
3089                 else if (cmd.argument() == "wrap")
3090                         code = WRAP_CODE;
3091                 break;
3092
3093         case LFUN_ERT_INSERT:
3094                 code = ERT_CODE;
3095                 break;
3096         case LFUN_LISTING_INSERT:
3097                 code = LISTINGS_CODE;
3098                 // not allowed in description items
3099                 enable = !inDescriptionItem(cur);
3100                 break;
3101         case LFUN_FOOTNOTE_INSERT:
3102                 code = FOOT_CODE;
3103                 break;
3104         case LFUN_TABULAR_INSERT:
3105                 code = TABULAR_CODE;
3106                 break;
3107         case LFUN_TABULAR_STYLE_INSERT:
3108                 code = TABULAR_CODE;
3109                 break;
3110         case LFUN_MARGINALNOTE_INSERT:
3111                 code = MARGIN_CODE;
3112                 break;
3113         case LFUN_FLOAT_INSERT:
3114         case LFUN_FLOAT_WIDE_INSERT:
3115                 // FIXME: If there is a selection, we should check whether there
3116                 // are floats in the selection, but this has performance issues, see
3117                 // LFUN_CHANGE_ACCEPT/REJECT.
3118                 code = FLOAT_CODE;
3119                 if (inDescriptionItem(cur))
3120                         // not allowed in description items
3121                         enable = false;
3122                 else {
3123                         InsetCode const inset_code = cur.inset().lyxCode();
3124
3125                         // algorithm floats cannot be put in another float
3126                         if (to_utf8(cmd.argument()) == "algorithm") {
3127                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
3128                                 break;
3129                         }
3130
3131                         // for figures and tables: only allow in another
3132                         // float or wrap if it is of the same type and
3133                         // not a subfloat already
3134                         if(cur.inset().lyxCode() == code) {
3135                                 InsetFloat const & ins =
3136                                         static_cast<InsetFloat const &>(cur.inset());
3137                                 enable = ins.params().type == to_utf8(cmd.argument())
3138                                         && !ins.params().subfloat;
3139                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
3140                                 InsetWrap const & ins =
3141                                         static_cast<InsetWrap const &>(cur.inset());
3142                                 enable = ins.params().type == to_utf8(cmd.argument());
3143                         }
3144                 }
3145                 break;
3146         case LFUN_WRAP_INSERT:
3147                 code = WRAP_CODE;
3148                 // not allowed in description items
3149                 enable = !inDescriptionItem(cur);
3150                 break;
3151         case LFUN_FLOAT_LIST_INSERT: {
3152                 code = FLOAT_LIST_CODE;
3153                 // not allowed in description items
3154                 enable = !inDescriptionItem(cur);
3155                 if (enable) {
3156                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
3157                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
3158                         // make sure we know about such floats
3159                         if (cit == floats.end() ||
3160                                         // and that we know how to generate a list of them
3161                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
3162                                 status.setUnknown(true);
3163                                 // probably not necessary, but...
3164                                 enable = false;
3165                         }
3166                 }
3167                 break;
3168         }
3169         case LFUN_CAPTION_INSERT: {
3170                 code = CAPTION_CODE;
3171                 string arg = cmd.getArg(0);
3172                 bool varia = arg != "Unnumbered"
3173                         && cur.inset().allowsCaptionVariation(arg);
3174                 // not allowed in description items,
3175                 // and in specific insets
3176                 enable = !inDescriptionItem(cur)
3177                         && (varia || arg.empty() || arg == "Standard");
3178                 break;
3179         }
3180         case LFUN_NOTE_INSERT:
3181                 code = NOTE_CODE;
3182                 break;
3183         case LFUN_FLEX_INSERT: {
3184                 code = FLEX_CODE;
3185                 string s = cmd.getArg(0);
3186                 InsetLayout il =
3187                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
3188                 if (il.lyxtype() != InsetLyXType::CHARSTYLE &&
3189                     il.lyxtype() != InsetLyXType::CUSTOM &&
3190                     il.lyxtype ()!= InsetLyXType::STANDARD)
3191                         enable = false;
3192                 break;
3193                 }
3194         case LFUN_BOX_INSERT:
3195                 code = BOX_CODE;
3196                 break;
3197         case LFUN_BRANCH_INSERT:
3198                 code = BRANCH_CODE;
3199                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
3200                     && cur.buffer()->params().branchlist().empty())
3201                         enable = false;
3202                 break;
3203         case LFUN_IPA_INSERT:
3204                 code = IPA_CODE;
3205                 break;
3206         case LFUN_PHANTOM_INSERT:
3207                 code = PHANTOM_CODE;
3208                 break;
3209         case LFUN_LABEL_INSERT:
3210                 code = LABEL_CODE;
3211                 break;
3212         case LFUN_INFO_INSERT:
3213                 code = INFO_CODE;
3214                 enable = cmd.argument().empty()
3215                         || infoparams.validateArgument(cur.buffer(), cmd.argument(), true);
3216                 break;
3217         case LFUN_ARGUMENT_INSERT: {
3218                 code = ARG_CODE;
3219                 allow_in_passthru = true;
3220                 string const arg = cmd.getArg(0);
3221                 if (arg.empty()) {
3222                         enable = false;
3223                         break;
3224                 }
3225                 Layout const & lay = cur.paragraph().layout();
3226                 Layout::LaTeXArgMap args = lay.args();
3227                 Layout::LaTeXArgMap::const_iterator const lait =
3228                                 args.find(arg);
3229                 if (lait != args.end()) {
3230                         enable = true;
3231                         pit_type pit = cur.pit();
3232                         pit_type lastpit = cur.pit();
3233                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
3234                                 // In a sequence of "merged" environment layouts, we only allow
3235                                 // non-item arguments once.
3236                                 lastpit = cur.lastpit();
3237                                 // get the first paragraph in sequence with this layout
3238                                 depth_type const current_depth = cur.paragraph().params().depth();
3239                                 while (true) {
3240                                         if (pit == 0)
3241                                                 break;
3242                                         Paragraph cpar = pars_[pit - 1];
3243                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
3244                                                 --pit;
3245                                         else
3246                                                 break;
3247                                 }
3248                         }
3249                         for (; pit <= lastpit; ++pit) {
3250                                 if (pars_[pit].layout() != lay)
3251                                         break;
3252                                 for (auto const & table : pars_[pit].insetList())
3253                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
3254                                                 if (ins->name() == arg) {
3255                                                         // we have this already
3256                                                         enable = false;
3257                                                         break;
3258                                                 }
3259                         }
3260                 } else
3261                         enable = false;
3262                 break;
3263         }
3264         case LFUN_INDEX_INSERT:
3265                 code = INDEX_CODE;
3266                 break;
3267         case LFUN_INDEX_PRINT:
3268                 code = INDEX_PRINT_CODE;
3269                 // not allowed in description items
3270                 enable = !inDescriptionItem(cur);
3271                 break;
3272         case LFUN_NOMENCL_INSERT:
3273                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3274                         enable = false;
3275                         break;
3276                 }
3277                 code = NOMENCL_CODE;
3278                 break;
3279         case LFUN_NOMENCL_PRINT:
3280                 code = NOMENCL_PRINT_CODE;
3281                 // not allowed in description items
3282                 enable = !inDescriptionItem(cur);
3283                 break;
3284         case LFUN_HREF_INSERT:
3285                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3286                         enable = false;
3287                         break;
3288                 }
3289                 code = HYPERLINK_CODE;
3290                 break;
3291         case LFUN_IPAMACRO_INSERT: {
3292                 string const arg = cmd.getArg(0);
3293                 if (arg == "deco")
3294                         code = IPADECO_CODE;
3295                 else
3296                         code = IPACHAR_CODE;
3297                 break;
3298         }
3299         case LFUN_QUOTE_INSERT:
3300                 // always allow this, since we will inset a raw quote
3301                 // if an inset is not allowed.
3302                 allow_in_passthru = true;
3303                 break;
3304         case LFUN_SPECIALCHAR_INSERT:
3305                 code = SPECIALCHAR_CODE;
3306                 break;
3307         case LFUN_SPACE_INSERT:
3308                 // slight hack: we know this is allowed in math mode
3309                 if (cur.inTexted())
3310                         code = SPACE_CODE;
3311                 break;
3312         case LFUN_PREVIEW_INSERT:
3313                 code = PREVIEW_CODE;
3314                 break;
3315         case LFUN_SCRIPT_INSERT:
3316                 code = SCRIPT_CODE;
3317                 break;
3318
3319         case LFUN_MATH_INSERT:
3320         case LFUN_MATH_AMS_MATRIX:
3321         case LFUN_MATH_MATRIX:
3322         case LFUN_MATH_DELIM:
3323         case LFUN_MATH_BIGDELIM:
3324         case LFUN_MATH_DISPLAY:
3325         case LFUN_MATH_MODE:
3326         case LFUN_MATH_MACRO:
3327         case LFUN_MATH_SUBSCRIPT:
3328         case LFUN_MATH_SUPERSCRIPT:
3329                 code = MATH_HULL_CODE;
3330                 break;
3331
3332         case LFUN_REGEXP_MODE:
3333                 code = MATH_HULL_CODE;
3334                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3335                 break;
3336
3337         case LFUN_INSET_MODIFY:
3338                 // We need to disable this, because we may get called for a
3339                 // tabular cell via
3340                 // InsetTabular::getStatus() -> InsetText::getStatus()
3341                 // and we don't handle LFUN_INSET_MODIFY.
3342                 enable = false;
3343                 break;
3344
3345         case LFUN_FONT_EMPH:
3346                 status.setOnOff(fontinfo.emph() == FONT_ON);
3347                 enable = !cur.paragraph().isPassThru();
3348                 break;
3349
3350         case LFUN_FONT_ITAL:
3351                 status.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3352                 enable = !cur.paragraph().isPassThru();
3353                 break;
3354
3355         case LFUN_FONT_NOUN:
3356                 status.setOnOff(fontinfo.noun() == FONT_ON);
3357                 enable = !cur.paragraph().isPassThru();
3358                 break;
3359
3360         case LFUN_FONT_BOLD:
3361         case LFUN_FONT_BOLDSYMBOL:
3362                 status.setOnOff(fontinfo.series() == BOLD_SERIES);
3363                 enable = !cur.paragraph().isPassThru();
3364                 break;
3365
3366         case LFUN_FONT_SANS:
3367                 status.setOnOff(fontinfo.family() == SANS_FAMILY);
3368                 enable = !cur.paragraph().isPassThru();
3369                 break;
3370
3371         case LFUN_FONT_ROMAN:
3372                 status.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3373                 enable = !cur.paragraph().isPassThru();
3374                 break;
3375
3376         case LFUN_FONT_TYPEWRITER:
3377                 status.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3378                 enable = !cur.paragraph().isPassThru();
3379                 break;
3380
3381         case LFUN_CUT:
3382                 enable = cur.selection();
3383                 break;
3384
3385         case LFUN_PASTE: {
3386                 if (cmd.argument().empty()) {
3387                         if (theClipboard().isInternal())
3388                                 enable = cap::numberOfSelections() > 0;
3389                         else
3390                                 enable = !theClipboard().empty();
3391                         break;
3392                 }
3393
3394                 // we have an argument
3395                 string const arg = to_utf8(cmd.argument());
3396                 if (isStrUnsignedInt(arg)) {
3397                         // it's a number and therefore means the internal stack
3398                         unsigned int n = convert<unsigned int>(arg);
3399                         enable = cap::numberOfSelections() > n;
3400                         break;
3401                 }
3402
3403                 // explicit text type?
3404                 if (arg == "html") {
3405                         // Do not enable for PlainTextType, since some tidying in the
3406                         // frontend is needed for HTML, which is too unsafe for plain text.
3407                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3408                         break;
3409                 } else if (arg == "latex") {
3410                         // LaTeX is usually not available on the clipboard with
3411                         // the correct MIME type, but in plain text.
3412                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3413                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3414                         break;
3415                 }
3416
3417                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3418                 if (arg == "pdf")
3419                         type = Clipboard::PdfGraphicsType;
3420                 else if (arg == "png")
3421                         type = Clipboard::PngGraphicsType;
3422                 else if (arg == "jpeg")
3423                         type = Clipboard::JpegGraphicsType;
3424                 else if (arg == "linkback")
3425                         type = Clipboard::LinkBackGraphicsType;
3426                 else if (arg == "emf")
3427                         type = Clipboard::EmfGraphicsType;
3428                 else if (arg == "wmf")
3429                         type = Clipboard::WmfGraphicsType;
3430                 else {
3431                         // unknown argument
3432                         LYXERR0("Unrecognized graphics type: " << arg);
3433                         // we don't want to assert if the user just mistyped the LFUN
3434                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3435                         enable = false;
3436                         break;
3437                 }
3438                 enable = theClipboard().hasGraphicsContents(type);
3439                 break;
3440         }
3441
3442         case LFUN_CLIPBOARD_PASTE:
3443         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3444                 enable = !theClipboard().empty();
3445                 break;
3446
3447         case LFUN_PRIMARY_SELECTION_PASTE:
3448                 status.setUnknown(!theSelection().supported());
3449                 enable = cur.selection() || !theSelection().empty();
3450                 break;
3451
3452         case LFUN_SELECTION_PASTE:
3453                 enable = cap::selection();
3454                 break;
3455
3456         case LFUN_PARAGRAPH_MOVE_UP:
3457                 enable = cur.pit() > 0 && !cur.selection();
3458                 break;
3459
3460         case LFUN_PARAGRAPH_MOVE_DOWN:
3461                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3462                 break;
3463
3464         case LFUN_CHANGE_ACCEPT:
3465         case LFUN_CHANGE_REJECT:
3466                 if (!cur.selection())
3467                         enable = cur.paragraph().isChanged(cur.pos());
3468                 else {
3469                         // will enable if there is a change in the selection
3470                         enable = false;
3471
3472                         // cheap improvement for efficiency: using cached
3473                         // buffer variable, if there is no change in the
3474                         // document, no need to check further.
3475                         if (!cur.buffer()->areChangesPresent())
3476                                 break;
3477
3478                         for (DocIterator it = cur.selectionBegin(); ; it.forwardPar()) {
3479                                 pos_type const beg = it.pos();
3480                                 pos_type end;
3481                                 bool const in_last_par = (it.pit() == cur.selectionEnd().pit() &&
3482                                                           it.idx() == cur.selectionEnd().idx());
3483                                 if (in_last_par)
3484                                         end = cur.selectionEnd().pos();
3485                                 else
3486                                         // the +1 is needed for cases, e.g., where there is a
3487                                         // paragraph break. See #11629.
3488                                         end = it.lastpos() + 1;
3489                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3490                                         enable = true;
3491                                         break;
3492                                 }
3493                                 if (beg != end && it.paragraph().hasChangedInsets(beg, end)) {
3494                                         enable = true;
3495                                         break;
3496                                 }
3497                                 if (in_last_par)
3498                                         break;
3499                         }
3500                 }
3501                 break;
3502
3503         case LFUN_OUTLINE_UP:
3504         case LFUN_OUTLINE_DOWN:
3505         case LFUN_OUTLINE_IN:
3506         case LFUN_OUTLINE_OUT:
3507                 // FIXME: LyX is not ready for outlining within inset.
3508                 enable = isMainText()
3509                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3510                 break;
3511
3512         case LFUN_NEWLINE_INSERT:
3513                 // LaTeX restrictions (labels or empty par)
3514                 enable = !cur.paragraph().isPassThru()
3515                         && cur.pos() > cur.paragraph().beginOfBody();
3516                 break;
3517
3518         case LFUN_SEPARATOR_INSERT:
3519                 // Always enabled for now
3520                 enable = true;
3521                 break;
3522
3523         case LFUN_TAB_INSERT:
3524         case LFUN_TAB_DELETE:
3525                 enable = cur.paragraph().isPassThru();
3526                 break;
3527
3528         case LFUN_GRAPHICS_SET_GROUP: {
3529                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3530                 if (!ins)
3531                         enable = false;
3532                 else
3533                         status.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3534                 break;
3535         }
3536
3537         case LFUN_NEWPAGE_INSERT:
3538                 // not allowed in description items
3539                 code = NEWPAGE_CODE;
3540                 enable = !inDescriptionItem(cur);
3541                 break;
3542
3543         case LFUN_LANGUAGE:
3544                 enable = !cur.paragraph().isPassThru();
3545                 status.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3546                 break;
3547
3548         case LFUN_PARAGRAPH_BREAK:
3549                 enable = inset().allowMultiPar();
3550                 break;
3551
3552         case LFUN_SPELLING_ADD:
3553         case LFUN_SPELLING_ADD_LOCAL:
3554         case LFUN_SPELLING_REMOVE_LOCAL:
3555         case LFUN_SPELLING_IGNORE:
3556         case LFUN_SPELLING_REMOVE:
3557                 enable = theSpellChecker() != nullptr;
3558                 if (enable && !cmd.getArg(1).empty()) {
3559                         // validate explicitly given language
3560                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3561                         enable &= lang != nullptr;
3562                 }
3563                 break;
3564
3565         case LFUN_LAYOUT:
3566         case LFUN_LAYOUT_TOGGLE: {
3567                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3568                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3569                 docstring const layout = resolveLayout(req_layout, cur);
3570
3571                 // FIXME: make this work in multicell selection case
3572                 enable = !owner_->forcePlainLayout() && !layout.empty() && !cur.selIsMultiCell();
3573                 status.setOnOff(!owner_->forcePlainLayout() && !cur.selIsMultiCell()
3574                                 && isAlreadyLayout(layout, cur));
3575                 break;
3576         }
3577
3578         case LFUN_ENVIRONMENT_SPLIT: {
3579                 if (cmd.argument() == "outer") {
3580                         // check if we have an environment in our nesting hierarchy
3581                         bool res = false;
3582                         depth_type const current_depth = cur.paragraph().params().depth();
3583                         pit_type pit = cur.pit();
3584                         Paragraph cpar = pars_[pit];
3585                         while (true) {
3586                                 if (pit == 0 || cpar.params().depth() == 0)
3587                                         break;
3588                                 --pit;
3589                                 cpar = pars_[pit];
3590                                 if (cpar.params().depth() < current_depth)
3591                                         res = cpar.layout().isEnvironment();
3592                         }
3593                         enable = res;
3594                         break;
3595                 }
3596                 else if (cmd.argument() == "previous") {
3597                         // look if we have an environment in the previous par
3598                         pit_type pit = cur.pit();
3599                         Paragraph cpar = pars_[pit];
3600                         if (pit > 0) {
3601                                 --pit;
3602                                 cpar = pars_[pit];
3603                                 enable = cpar.layout().isEnvironment();
3604                                 break;
3605                         }
3606                         enable = false;
3607                         break;
3608                 }
3609                 else if (cur.paragraph().layout().isEnvironment()) {
3610                         enable = cmd.argument() == "before"
3611                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3612                         break;
3613                 }
3614                 enable = false;
3615                 break;
3616         }
3617
3618         case LFUN_LAYOUT_PARAGRAPH:
3619         case LFUN_PARAGRAPH_PARAMS:
3620         case LFUN_PARAGRAPH_PARAMS_APPLY:
3621         case LFUN_PARAGRAPH_UPDATE:
3622                 enable = owner_->allowParagraphCustomization();
3623                 break;
3624
3625         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3626         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3627         //  that cannot be handled by LaTeX but must be converted according
3628         //  to the definition in lib/unicodesymbols?
3629         case LFUN_ACCENT_ACUTE:
3630         case LFUN_ACCENT_BREVE:
3631         case LFUN_ACCENT_CARON:
3632         case LFUN_ACCENT_CEDILLA:
3633         case LFUN_ACCENT_CIRCLE:
3634         case LFUN_ACCENT_CIRCUMFLEX:
3635         case LFUN_ACCENT_DOT:
3636         case LFUN_ACCENT_GRAVE:
3637         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3638         case LFUN_ACCENT_MACRON:
3639         case LFUN_ACCENT_OGONEK:
3640         case LFUN_ACCENT_TIE:
3641         case LFUN_ACCENT_TILDE:
3642         case LFUN_ACCENT_PERISPOMENI:
3643         case LFUN_ACCENT_UMLAUT:
3644         case LFUN_ACCENT_UNDERBAR:
3645         case LFUN_ACCENT_UNDERDOT:
3646         case LFUN_FONT_FRAK:
3647         case LFUN_FONT_SIZE:
3648         case LFUN_FONT_STATE:
3649         case LFUN_FONT_UNDERLINE:
3650         case LFUN_FONT_STRIKEOUT:
3651         case LFUN_FONT_CROSSOUT:
3652         case LFUN_FONT_UNDERUNDERLINE:
3653         case LFUN_FONT_UNDERWAVE:
3654         case LFUN_FONT_NO_SPELLCHECK:
3655         case LFUN_TEXTSTYLE_UPDATE:
3656                 enable = !cur.paragraph().isPassThru();
3657                 break;
3658
3659         case LFUN_FONT_DEFAULT: {
3660                 Font font(inherit_font, ignore_language);
3661                 BufferParams const & bp = cur.buffer()->masterParams();
3662                 if (cur.selection()) {
3663                         enable = false;
3664                         // Check if we have a non-default font attribute
3665                         // in the selection range.
3666                         DocIterator const from = cur.selectionBegin();
3667                         DocIterator const to = cur.selectionEnd();
3668                         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
3669                                 if (!dit.inTexted()) {
3670                                         dit.forwardPos();
3671                                         continue;
3672                                 }
3673                                 Paragraph const & par = dit.paragraph();
3674                                 pos_type const pos = dit.pos();
3675                                 Font tmp = par.getFontSettings(bp, pos);
3676                                 if (tmp.fontInfo() != font.fontInfo()
3677                                     || tmp.language() != bp.language) {
3678                                         enable = true;
3679                                         break;
3680                                 }
3681                                 dit.forwardPos();
3682                         }
3683                         break;
3684                 }
3685                 // Disable if all is default already.
3686                 enable = (cur.current_font.fontInfo() != font.fontInfo()
3687                           || cur.current_font.language() != bp.language);
3688                 break;
3689         }
3690
3691         case LFUN_TEXTSTYLE_APPLY:
3692                 enable = !freeFonts.empty();
3693                 break;
3694
3695         case LFUN_WORD_DELETE_FORWARD:
3696         case LFUN_WORD_DELETE_BACKWARD:
3697         case LFUN_LINE_DELETE_FORWARD:
3698         case LFUN_WORD_FORWARD:
3699         case LFUN_WORD_BACKWARD:
3700         case LFUN_WORD_RIGHT:
3701         case LFUN_WORD_LEFT:
3702         case LFUN_CHAR_FORWARD:
3703         case LFUN_CHAR_FORWARD_SELECT:
3704         case LFUN_CHAR_BACKWARD:
3705         case LFUN_CHAR_BACKWARD_SELECT:
3706         case LFUN_CHAR_LEFT:
3707         case LFUN_CHAR_LEFT_SELECT:
3708         case LFUN_CHAR_RIGHT:
3709         case LFUN_CHAR_RIGHT_SELECT:
3710         case LFUN_UP:
3711         case LFUN_UP_SELECT:
3712         case LFUN_DOWN:
3713         case LFUN_DOWN_SELECT:
3714         case LFUN_PARAGRAPH_SELECT:
3715         case LFUN_PARAGRAPH_UP_SELECT:
3716         case LFUN_PARAGRAPH_DOWN_SELECT:
3717         case LFUN_LINE_BEGIN_SELECT:
3718         case LFUN_LINE_END_SELECT:
3719         case LFUN_WORD_FORWARD_SELECT:
3720         case LFUN_WORD_BACKWARD_SELECT:
3721         case LFUN_WORD_RIGHT_SELECT:
3722         case LFUN_WORD_LEFT_SELECT:
3723         case LFUN_WORD_SELECT:
3724         case LFUN_SECTION_SELECT:
3725         case LFUN_BUFFER_BEGIN:
3726         case LFUN_BUFFER_END:
3727         case LFUN_BUFFER_BEGIN_SELECT:
3728         case LFUN_BUFFER_END_SELECT:
3729         case LFUN_INSET_BEGIN:
3730         case LFUN_INSET_END:
3731         case LFUN_INSET_BEGIN_SELECT:
3732         case LFUN_INSET_END_SELECT:
3733         case LFUN_PARAGRAPH_UP:
3734         case LFUN_PARAGRAPH_DOWN:
3735         case LFUN_LINE_BEGIN:
3736         case LFUN_LINE_END:
3737         case LFUN_CHAR_DELETE_FORWARD:
3738         case LFUN_CHAR_DELETE_BACKWARD:
3739         case LFUN_WORD_UPCASE:
3740         case LFUN_WORD_LOWCASE:
3741         case LFUN_WORD_CAPITALIZE:
3742         case LFUN_CHARS_TRANSPOSE:
3743         case LFUN_SERVER_GET_XY:
3744         case LFUN_SERVER_SET_XY:
3745         case LFUN_SERVER_GET_LAYOUT:
3746         case LFUN_SELF_INSERT:
3747         case LFUN_UNICODE_INSERT:
3748         case LFUN_THESAURUS_ENTRY:
3749         case LFUN_ESCAPE:
3750         case LFUN_SERVER_GET_STATISTICS:
3751                 // these are handled in our dispatch()
3752                 enable = true;
3753                 break;
3754
3755         case LFUN_INSET_INSERT: {
3756                 string const type = cmd.getArg(0);
3757                 if (type == "toc") {
3758                         code = TOC_CODE;
3759                         // not allowed in description items
3760                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3761                         enable = !inDescriptionItem(cur);
3762                 } else {
3763                         enable = true;
3764                 }
3765                 break;
3766         }
3767
3768         case LFUN_SEARCH_IGNORE: {
3769                 bool const value = cmd.getArg(1) == "true";
3770                 setIgnoreFormat(cmd.getArg(0), value);
3771                 break;
3772         }
3773
3774         default:
3775                 return false;
3776         }
3777
3778         if (code != NO_CODE
3779             && (cur.empty()
3780                 || !cur.inset().insetAllowed(code)
3781                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3782                 enable = false;
3783
3784         status.setEnabled(enable);
3785         return true;
3786 }
3787
3788
3789 void Text::pasteString(Cursor & cur, docstring const & clip,
3790                 bool asParagraphs)
3791 {
3792         if (!clip.empty()) {
3793                 cur.recordUndo();
3794                 if (asParagraphs)
3795                         insertStringAsParagraphs(cur, clip, cur.current_font);
3796                 else
3797                         insertStringAsLines(cur, clip, cur.current_font);
3798         }
3799 }
3800
3801
3802 // FIXME: an item inset would make things much easier.
3803 bool Text::inDescriptionItem(Cursor const & cur) const
3804 {
3805         Paragraph const & par = cur.paragraph();
3806         pos_type const pos = cur.pos();
3807         pos_type const body_pos = par.beginOfBody();
3808
3809         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3810             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3811                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3812                 return false;
3813
3814         return (pos < body_pos
3815                 || (pos == body_pos
3816                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3817 }
3818
3819
3820 std::vector<docstring> Text::getFreeFonts() const
3821 {
3822         vector<docstring> ffList;
3823
3824         for (auto const & f : freeFonts)
3825                 ffList.push_back(f.first);
3826
3827         return ffList;
3828 }
3829
3830 } // namespace lyx