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