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