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