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