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