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