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