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