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