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