]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Fix text direction issue for InsetInfo in RTL context
[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                 Inset * inset;
2000                 if (cmd.argument().empty() && cur.selection()) {
2001                         // if command argument is empty use current selection as parameter.
2002                         docstring ds = cur.selectionAsString(false);
2003                         cutSelection(cur, false);
2004                         FuncRequest cmd0(cmd, ds);
2005                         inset = createInset(cur.buffer(), cmd0);
2006                 } else {
2007                         inset = createInset(cur.buffer(), cmd);
2008                 }
2009                 if (!inset)
2010                         break;
2011                 cur.recordUndo();
2012                 insertInset(cur, inset);
2013                 cur.forceBufferUpdate();
2014                 cur.posForward();
2015                 break;
2016         }
2017         case LFUN_CAPTION_INSERT:
2018         case LFUN_FOOTNOTE_INSERT:
2019         case LFUN_NOTE_INSERT:
2020         case LFUN_BOX_INSERT:
2021         case LFUN_BRANCH_INSERT:
2022         case LFUN_PHANTOM_INSERT:
2023         case LFUN_ERT_INSERT:
2024         case LFUN_LISTING_INSERT:
2025         case LFUN_MARGINALNOTE_INSERT:
2026         case LFUN_ARGUMENT_INSERT:
2027         case LFUN_INDEX_INSERT:
2028         case LFUN_PREVIEW_INSERT:
2029         case LFUN_SCRIPT_INSERT:
2030         case LFUN_IPA_INSERT:
2031                 // Open the inset, and move the current selection
2032                 // inside it.
2033                 doInsertInset(cur, this, cmd, true, true);
2034                 cur.posForward();
2035                 // Some insets are numbered, others are shown in the outline pane so
2036                 // let's update the labels and the toc backend.
2037                 cur.forceBufferUpdate();
2038                 break;
2039
2040         case LFUN_FLEX_INSERT: {
2041                 // Open the inset, and move the current selection
2042                 // inside it.
2043                 bool const sel = cur.selection();
2044                 doInsertInset(cur, this, cmd, true, true);
2045                 // Insert auto-insert arguments
2046                 bool autoargs = false;
2047                 Layout::LaTeXArgMap args = cur.inset().getLayout().latexargs();
2048                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
2049                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
2050                 for (; lait != laend; ++lait) {
2051                         Layout::latexarg arg = (*lait).second;
2052                         if (arg.autoinsert) {
2053                                 // The cursor might have been invalidated by the replaceSelection.
2054                                 cur.buffer()->changed(true);
2055                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, (*lait).first);
2056                                 lyx::dispatch(cmd2);
2057                                 autoargs = true;
2058                         }
2059                 }
2060                 if (!autoargs) {
2061                         if (sel)
2062                                 cur.leaveInset(cur.inset());
2063                         cur.posForward();
2064                 }
2065                 // Some insets are numbered, others are shown in the outline pane so
2066                 // let's update the labels and the toc backend.
2067                 cur.forceBufferUpdate();
2068                 break;
2069         }
2070
2071         case LFUN_TABULAR_INSERT:
2072                 // if there were no arguments, just open the dialog
2073                 if (doInsertInset(cur, this, cmd, false, true))
2074                         cur.posForward();
2075                 else
2076                         bv->showDialog("tabularcreate");
2077
2078                 break;
2079
2080         case LFUN_FLOAT_INSERT:
2081         case LFUN_FLOAT_WIDE_INSERT:
2082         case LFUN_WRAP_INSERT: {
2083                 // will some content be moved into the inset?
2084                 bool const content = cur.selection();
2085                 // does the content consist of multiple paragraphs?
2086                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2087
2088                 doInsertInset(cur, this, cmd, true, true);
2089                 cur.posForward();
2090
2091                 // If some single-par content is moved into the inset,
2092                 // doInsertInset puts the cursor outside the inset.
2093                 // To insert the caption we put it back into the inset.
2094                 // FIXME cleanup doInsertInset to avoid such dances!
2095                 if (content && singlepar)
2096                         cur.backwardPos();
2097
2098                 ParagraphList & pars = cur.text()->paragraphs();
2099
2100                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2101
2102                 // add a separate paragraph for the caption inset
2103                 pars.push_back(Paragraph());
2104                 pars.back().setInsetOwner(&cur.text()->inset());
2105                 pars.back().setPlainOrDefaultLayout(tclass);
2106                 int cap_pit = pars.size() - 1;
2107
2108                 // if an empty inset was created, we create an additional empty
2109                 // paragraph at the bottom so that the user can choose where to put
2110                 // the graphics (or table).
2111                 if (!content) {
2112                         pars.push_back(Paragraph());
2113                         pars.back().setInsetOwner(&cur.text()->inset());
2114                         pars.back().setPlainOrDefaultLayout(tclass);
2115                 }
2116
2117                 // reposition the cursor to the caption
2118                 cur.pit() = cap_pit;
2119                 cur.pos() = 0;
2120                 // FIXME: This Text/Cursor dispatch handling is a mess!
2121                 // We cannot use Cursor::dispatch here it needs access to up to
2122                 // date metrics.
2123                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2124                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2125                 cur.forceBufferUpdate();
2126                 cur.screenUpdateFlags(Update::Force);
2127                 // FIXME: When leaving the Float (or Wrap) inset we should
2128                 // delete any empty paragraph left above or below the
2129                 // caption.
2130                 break;
2131         }
2132
2133         case LFUN_NOMENCL_INSERT: {
2134                 InsetCommandParams p(NOMENCL_CODE);
2135                 if (cmd.argument().empty()) {
2136                         p["symbol"] = 
2137                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2138                         cur.clearSelection();
2139                 } else
2140                         p["symbol"] = cmd.argument();
2141                 string const data = InsetCommand::params2string(p);
2142                 bv->showDialog("nomenclature", data);
2143                 break;
2144         }
2145
2146         case LFUN_INDEX_PRINT: {
2147                 InsetCommandParams p(INDEX_PRINT_CODE);
2148                 if (cmd.argument().empty())
2149                         p["type"] = from_ascii("idx");
2150                 else
2151                         p["type"] = cmd.argument();
2152                 string const data = InsetCommand::params2string(p);
2153                 FuncRequest fr(LFUN_INSET_INSERT, data);
2154                 dispatch(cur, fr);
2155                 break;
2156         }
2157
2158         case LFUN_NOMENCL_PRINT:
2159         case LFUN_NEWPAGE_INSERT:
2160                 // do nothing fancy
2161                 doInsertInset(cur, this, cmd, false, false);
2162                 cur.posForward();
2163                 break;
2164
2165         case LFUN_SEPARATOR_INSERT: {
2166                 doInsertInset(cur, this, cmd, false, false);
2167                 cur.posForward();
2168                 // remove a following space
2169                 Paragraph & par = cur.paragraph();
2170                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2171                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2172                 break;
2173         }
2174
2175         case LFUN_DEPTH_DECREMENT:
2176                 changeDepth(cur, DEC_DEPTH);
2177                 break;
2178
2179         case LFUN_DEPTH_INCREMENT:
2180                 changeDepth(cur, INC_DEPTH);
2181                 break;
2182
2183         case LFUN_REGEXP_MODE:
2184                 regexpDispatch(cur, cmd);
2185                 break;
2186
2187         case LFUN_MATH_MODE: {
2188                 if (cmd.argument() == "on" || cmd.argument() == "") {
2189                         // don't pass "on" as argument
2190                         // (it would appear literally in the first cell)
2191                         docstring sel = cur.selectionAsString(false);
2192                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2193                         // create a macro template if we see "\\newcommand" somewhere, and
2194                         // an ordinary formula otherwise
2195                         if (!sel.empty()
2196                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2197                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2198                                         || sel.find(from_ascii("\\def")) != string::npos)
2199                                 && macro->fromString(sel)) {
2200                                 cur.recordUndo();
2201                                 replaceSelection(cur);
2202                                 cur.insert(macro);
2203                         } else {
2204                                 // no meaningful macro template was found
2205                                 delete macro;
2206                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2207                         }
2208                 } else
2209                         // The argument is meaningful
2210                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2211                         // has a different meaning in math mode
2212                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2213                 break;
2214         }
2215
2216         case LFUN_MATH_MACRO:
2217                 if (cmd.argument().empty())
2218                         cur.errorMessage(from_utf8(N_("Missing argument")));
2219                 else {
2220                         cur.recordUndo();
2221                         string s = to_utf8(cmd.argument());
2222                         string const s1 = token(s, ' ', 1);
2223                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2224                         string const s2 = token(s, ' ', 2);
2225                         MacroType type = MacroTypeNewcommand;
2226                         if (s2 == "def")
2227                                 type = MacroTypeDef;
2228                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2229                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2230                         inset->setBuffer(bv->buffer());
2231                         insertInset(cur, inset);
2232
2233                         // enter macro inset and select the name
2234                         cur.push(*inset);
2235                         cur.top().pos() = cur.top().lastpos();
2236                         cur.resetAnchor();
2237                         cur.selection(true);
2238                         cur.top().pos() = 0;
2239                 }
2240                 break;
2241
2242         case LFUN_MATH_DISPLAY:
2243         case LFUN_MATH_SUBSCRIPT:
2244         case LFUN_MATH_SUPERSCRIPT:
2245         case LFUN_MATH_INSERT:
2246         case LFUN_MATH_AMS_MATRIX:
2247         case LFUN_MATH_MATRIX:
2248         case LFUN_MATH_DELIM:
2249         case LFUN_MATH_BIGDELIM:
2250                 mathDispatch(cur, cmd);
2251                 break;
2252
2253         case LFUN_FONT_EMPH: {
2254                 Font font(ignore_font, ignore_language);
2255                 font.fontInfo().setEmph(FONT_TOGGLE);
2256                 toggleAndShow(cur, this, font);
2257                 break;
2258         }
2259
2260         case LFUN_FONT_ITAL: {
2261                 Font font(ignore_font, ignore_language);
2262                 font.fontInfo().setShape(ITALIC_SHAPE);
2263                 toggleAndShow(cur, this, font);
2264                 break;
2265         }
2266
2267         case LFUN_FONT_BOLD:
2268         case LFUN_FONT_BOLDSYMBOL: {
2269                 Font font(ignore_font, ignore_language);
2270                 font.fontInfo().setSeries(BOLD_SERIES);
2271                 toggleAndShow(cur, this, font);
2272                 break;
2273         }
2274
2275         case LFUN_FONT_NOUN: {
2276                 Font font(ignore_font, ignore_language);
2277                 font.fontInfo().setNoun(FONT_TOGGLE);
2278                 toggleAndShow(cur, this, font);
2279                 break;
2280         }
2281
2282         case LFUN_FONT_TYPEWRITER: {
2283                 Font font(ignore_font, ignore_language);
2284                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2285                 toggleAndShow(cur, this, font);
2286                 break;
2287         }
2288
2289         case LFUN_FONT_SANS: {
2290                 Font font(ignore_font, ignore_language);
2291                 font.fontInfo().setFamily(SANS_FAMILY);
2292                 toggleAndShow(cur, this, font);
2293                 break;
2294         }
2295
2296         case LFUN_FONT_ROMAN: {
2297                 Font font(ignore_font, ignore_language);
2298                 font.fontInfo().setFamily(ROMAN_FAMILY);
2299                 toggleAndShow(cur, this, font);
2300                 break;
2301         }
2302
2303         case LFUN_FONT_DEFAULT: {
2304                 Font font(inherit_font, ignore_language);
2305                 toggleAndShow(cur, this, font);
2306                 break;
2307         }
2308
2309         case LFUN_FONT_STRIKEOUT: {
2310                 Font font(ignore_font, ignore_language);
2311                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2312                 toggleAndShow(cur, this, font);
2313                 break;
2314         }
2315
2316         case LFUN_FONT_CROSSOUT: {
2317                 Font font(ignore_font, ignore_language);
2318                 font.fontInfo().setXout(FONT_TOGGLE);
2319                 toggleAndShow(cur, this, font);
2320                 break;
2321         }
2322
2323         case LFUN_FONT_UNDERUNDERLINE: {
2324                 Font font(ignore_font, ignore_language);
2325                 font.fontInfo().setUuline(FONT_TOGGLE);
2326                 toggleAndShow(cur, this, font);
2327                 break;
2328         }
2329
2330         case LFUN_FONT_UNDERWAVE: {
2331                 Font font(ignore_font, ignore_language);
2332                 font.fontInfo().setUwave(FONT_TOGGLE);
2333                 toggleAndShow(cur, this, font);
2334                 break;
2335         }
2336
2337         case LFUN_FONT_UNDERLINE: {
2338                 Font font(ignore_font, ignore_language);
2339                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2340                 toggleAndShow(cur, this, font);
2341                 break;
2342         }
2343
2344         case LFUN_FONT_SIZE: {
2345                 Font font(ignore_font, ignore_language);
2346                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2347                 toggleAndShow(cur, this, font);
2348                 break;
2349         }
2350
2351         case LFUN_LANGUAGE: {
2352                 string const lang_arg = cmd.getArg(0);
2353                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2354                 Language const * lang =
2355                         reset ? reset_language
2356                               : languages.getLanguage(lang_arg);
2357                 // we allow reset_language, which is 0, but only if it
2358                 // was requested via empty or "reset" arg.
2359                 if (!lang && !reset)
2360                         break;
2361                 bool const toggle = (cmd.getArg(1) != "set");
2362                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2363                 Font font(ignore_font, lang);
2364                 toggleAndShow(cur, this, font, toggle);
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                         cur.message(_("Character set"));
2383                 } else {
2384                         lyxerr << "Argument not ok";
2385                 }
2386                 break;
2387         }
2388
2389         case LFUN_FINISHED_LEFT:
2390                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2391                 // We're leaving an inset, going left. If the inset is LTR, we're
2392                 // leaving from the front, so we should not move (remain at --- but
2393                 // not in --- the inset). If the inset is RTL, move left, without
2394                 // entering the inset itself; i.e., move to after the inset.
2395                 if (cur.paragraph().getFontSettings(
2396                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2397                         cursorVisLeft(cur, true);
2398                 break;
2399
2400         case LFUN_FINISHED_RIGHT:
2401                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2402                 // We're leaving an inset, going right. If the inset is RTL, we're
2403                 // leaving from the front, so we should not move (remain at --- but
2404                 // not in --- the inset). If the inset is LTR, move right, without
2405                 // entering the inset itself; i.e., move to after the inset.
2406                 if (!cur.paragraph().getFontSettings(
2407                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2408                         cursorVisRight(cur, true);
2409                 break;
2410
2411         case LFUN_FINISHED_BACKWARD:
2412                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2413                 cur.setCurrentFont();
2414                 break;
2415
2416         case LFUN_FINISHED_FORWARD:
2417                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2418                 ++cur.pos();
2419                 cur.setCurrentFont();
2420                 break;
2421
2422         case LFUN_LAYOUT_PARAGRAPH: {
2423                 string data;
2424                 params2string(cur.paragraph(), data);
2425                 data = "show\n" + data;
2426                 bv->showDialog("paragraph", data);
2427                 break;
2428         }
2429
2430         case LFUN_PARAGRAPH_UPDATE: {
2431                 string data;
2432                 params2string(cur.paragraph(), data);
2433
2434                 // Will the paragraph accept changes from the dialog?
2435                 bool const accept =
2436                         cur.inset().allowParagraphCustomization(cur.idx());
2437
2438                 data = "update " + convert<string>(accept) + '\n' + data;
2439                 bv->updateDialog("paragraph", data);
2440                 break;
2441         }
2442
2443         case LFUN_ACCENT_UMLAUT:
2444         case LFUN_ACCENT_CIRCUMFLEX:
2445         case LFUN_ACCENT_GRAVE:
2446         case LFUN_ACCENT_ACUTE:
2447         case LFUN_ACCENT_TILDE:
2448         case LFUN_ACCENT_PERISPOMENI:
2449         case LFUN_ACCENT_CEDILLA:
2450         case LFUN_ACCENT_MACRON:
2451         case LFUN_ACCENT_DOT:
2452         case LFUN_ACCENT_UNDERDOT:
2453         case LFUN_ACCENT_UNDERBAR:
2454         case LFUN_ACCENT_CARON:
2455         case LFUN_ACCENT_BREVE:
2456         case LFUN_ACCENT_TIE:
2457         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2458         case LFUN_ACCENT_CIRCLE:
2459         case LFUN_ACCENT_OGONEK:
2460                 theApp()->handleKeyFunc(cmd.action());
2461                 if (!cmd.argument().empty())
2462                         // FIXME: Are all these characters encoded in one byte in utf8?
2463                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2464                 cur.screenUpdateFlags(Update::FitCursor);
2465                 break;
2466
2467         case LFUN_FLOAT_LIST_INSERT: {
2468                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2469                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2470                         cur.recordUndo();
2471                         if (cur.selection())
2472                                 cutSelection(cur, false);
2473                         breakParagraph(cur);
2474
2475                         if (cur.lastpos() != 0) {
2476                                 cursorBackward(cur);
2477                                 breakParagraph(cur);
2478                         }
2479
2480                         docstring const laystr = cur.inset().usePlainLayout() ?
2481                                 tclass.plainLayoutName() :
2482                                 tclass.defaultLayoutName();
2483                         setLayout(cur, laystr);
2484                         ParagraphParameters p;
2485                         // FIXME If this call were replaced with one to clearParagraphParams(),
2486                         // then we could get rid of this method altogether.
2487                         setParagraphs(cur, p);
2488                         // FIXME This should be simplified when InsetFloatList takes a
2489                         // Buffer in its constructor.
2490                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2491                         ifl->setBuffer(bv->buffer());
2492                         insertInset(cur, ifl);
2493                         cur.posForward();
2494                 } else {
2495                         lyxerr << "Non-existent float type: "
2496                                << to_utf8(cmd.argument()) << endl;
2497                 }
2498                 break;
2499         }
2500
2501         case LFUN_CHANGE_ACCEPT: {
2502                 acceptOrRejectChanges(cur, ACCEPT);
2503                 break;
2504         }
2505
2506         case LFUN_CHANGE_REJECT: {
2507                 acceptOrRejectChanges(cur, REJECT);
2508                 break;
2509         }
2510
2511         case LFUN_THESAURUS_ENTRY: {
2512                 Language const * language = cur.getFont().language();
2513                 docstring arg = cmd.argument();
2514                 if (arg.empty()) {
2515                         arg = cur.selectionAsString(false);
2516                         // FIXME
2517                         if (arg.size() > 100 || arg.empty()) {
2518                                 // Get word or selection
2519                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2520                                 arg = cur.selectionAsString(false);
2521                                 arg += " lang=" + from_ascii(language->lang());
2522                         }
2523                 } else {
2524                         string lang = cmd.getArg(1);
2525                         // This duplicates the code in GuiThesaurus::initialiseParams
2526                         if (prefixIs(lang, "lang=")) {
2527                                 language = languages.getLanguage(lang.substr(5));
2528                                 if (!language)
2529                                         language = cur.getFont().language();
2530                         }
2531                 }
2532                 string lang = language->code();
2533                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2534                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2535                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2536                                         _("The path to the thesaurus directory has not been specified.\n"
2537                                           "The thesaurus is not functional.\n"
2538                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2539                                           "instructions."));
2540                 }
2541                 bv->showDialog("thesaurus", to_utf8(arg));
2542                 break;
2543         }
2544
2545         case LFUN_SPELLING_ADD: {
2546                 Language const * language = getLanguage(cur, cmd.getArg(1));
2547                 docstring word = from_utf8(cmd.getArg(0));
2548                 if (word.empty()) {
2549                         word = cur.selectionAsString(false);
2550                         // FIXME
2551                         if (word.size() > 100 || word.empty()) {
2552                                 // Get word or selection
2553                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2554                                 word = cur.selectionAsString(false);
2555                         }
2556                 }
2557                 WordLangTuple wl(word, language);
2558                 theSpellChecker()->insert(wl);
2559                 break;
2560         }
2561
2562         case LFUN_SPELLING_IGNORE: {
2563                 Language const * language = getLanguage(cur, cmd.getArg(1));
2564                 docstring word = from_utf8(cmd.getArg(0));
2565                 if (word.empty()) {
2566                         word = cur.selectionAsString(false);
2567                         // FIXME
2568                         if (word.size() > 100 || word.empty()) {
2569                                 // Get word or selection
2570                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2571                                 word = cur.selectionAsString(false);
2572                         }
2573                 }
2574                 WordLangTuple wl(word, language);
2575                 theSpellChecker()->accept(wl);
2576                 break;
2577         }
2578
2579         case LFUN_SPELLING_REMOVE: {
2580                 Language const * language = getLanguage(cur, cmd.getArg(1));
2581                 docstring word = from_utf8(cmd.getArg(0));
2582                 if (word.empty()) {
2583                         word = cur.selectionAsString(false);
2584                         // FIXME
2585                         if (word.size() > 100 || word.empty()) {
2586                                 // Get word or selection
2587                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2588                                 word = cur.selectionAsString(false);
2589                         }
2590                 }
2591                 WordLangTuple wl(word, language);
2592                 theSpellChecker()->remove(wl);
2593                 break;
2594         }
2595
2596         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2597                 // Given data, an encoding of the ParagraphParameters
2598                 // generated in the Paragraph dialog, this function sets
2599                 // the current paragraph, or currently selected paragraphs,
2600                 // appropriately.
2601                 // NOTE: This function overrides all existing settings.
2602                 setParagraphs(cur, cmd.argument());
2603                 cur.message(_("Paragraph layout set"));
2604                 break;
2605         }
2606
2607         case LFUN_PARAGRAPH_PARAMS: {
2608                 // Given data, an encoding of the ParagraphParameters as we'd
2609                 // find them in a LyX file, this function modifies the current paragraph,
2610                 // or currently selected paragraphs.
2611                 // NOTE: This function only modifies, and does not override, existing
2612                 // settings.
2613                 setParagraphs(cur, cmd.argument(), true);
2614                 cur.message(_("Paragraph layout set"));
2615                 break;
2616         }
2617
2618         case LFUN_ESCAPE:
2619                 if (cur.selection()) {
2620                         cur.selection(false);
2621                 } else {
2622                         cur.undispatched();
2623                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2624                         // correct, but I'm not 100% sure -- dov, 071019
2625                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2626                 }
2627                 break;
2628
2629         case LFUN_OUTLINE_UP:
2630                 outline(OutlineUp, cur, this);
2631                 setCursor(cur, cur.pit(), 0);
2632                 cur.forceBufferUpdate();
2633                 needsUpdate = true;
2634                 break;
2635
2636         case LFUN_OUTLINE_DOWN:
2637                 outline(OutlineDown, cur, this);
2638                 setCursor(cur, cur.pit(), 0);
2639                 cur.forceBufferUpdate();
2640                 needsUpdate = true;
2641                 break;
2642
2643         case LFUN_OUTLINE_IN:
2644                 outline(OutlineIn, cur, this);
2645                 cur.forceBufferUpdate();
2646                 needsUpdate = true;
2647                 break;
2648
2649         case LFUN_OUTLINE_OUT:
2650                 outline(OutlineOut, cur, this);
2651                 cur.forceBufferUpdate();
2652                 needsUpdate = true;
2653                 break;
2654
2655         case LFUN_SERVER_GET_STATISTICS:
2656                 {
2657                         DocIterator from, to;
2658                         if (cur.selection()) {
2659                                 from = cur.selectionBegin();
2660                                 to = cur.selectionEnd();
2661                         } else {
2662                                 from = doc_iterator_begin(cur.buffer());
2663                                 to = doc_iterator_end(cur.buffer());
2664                         }
2665
2666                         cur.buffer()->updateStatistics(from, to);
2667                         string const arg0 = cmd.getArg(0);
2668                         if (arg0 == "words") {
2669                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2670                         } else if (arg0 == "chars") {
2671                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2672                         } else if (arg0 == "chars-space") {
2673                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2674                         } else {
2675                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2676                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2677                                 + convert<docstring>(cur.buffer()->charCount(true)));
2678                         }
2679                 }
2680                 break;
2681
2682         default:
2683                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2684                 cur.undispatched();
2685                 break;
2686         }
2687
2688         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2689
2690         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2691                 // Check for misspelled text
2692                 // The redraw is useful because of the painting of
2693                 // misspelled markers depends on the cursor position.
2694                 // Trigger a redraw for cursor moves inside misspelled text.
2695                 if (!cur.inTexted()) {
2696                         // move from regular text to math
2697                         needsUpdate = last_misspelled;
2698                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2699                         // move inside regular text
2700                         needsUpdate = last_misspelled
2701                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2702                 }
2703         }
2704
2705         // FIXME: The cursor flag is reset two lines below
2706         // so we need to check here if some of the LFUN did touch that.
2707         // for now only Text::erase() and Text::backspace() do that.
2708         // The plan is to verify all the LFUNs and then to remove this
2709         // singleParUpdate boolean altogether.
2710         if (cur.result().screenUpdate() & Update::Force) {
2711                 singleParUpdate = false;
2712                 needsUpdate = true;
2713         }
2714
2715         // FIXME: the following code should go in favor of fine grained
2716         // update flag treatment.
2717         if (singleParUpdate) {
2718                 // Inserting characters does not change par height in general. So, try
2719                 // to update _only_ this paragraph. BufferView will detect if a full
2720                 // metrics update is needed anyway.
2721                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2722                 return;
2723         }
2724         if (!needsUpdate
2725             && &oldTopSlice.inset() == &cur.inset()
2726             && oldTopSlice.idx() == cur.idx()
2727             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2728             && !cur.selection())
2729                 // FIXME: it would be better if we could just do this
2730                 //
2731                 //if (cur.result().update() != Update::FitCursor)
2732                 //      cur.noScreenUpdate();
2733                 //
2734                 // But some LFUNs do not set Update::FitCursor when needed, so we
2735                 // do it for all. This is not very harmfull as FitCursor will provoke
2736                 // a full redraw only if needed but still, a proper review of all LFUN
2737                 // should be done and this needsUpdate boolean can then be removed.
2738                 cur.screenUpdateFlags(Update::FitCursor);
2739         else
2740                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2741 }
2742
2743
2744 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2745                         FuncStatus & flag) const
2746 {
2747         LBUFERR(this == cur.text());
2748
2749         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2750         bool enable = true;
2751         bool allow_in_passthru = false;
2752         InsetCode code = NO_CODE;
2753
2754         switch (cmd.action()) {
2755
2756         case LFUN_DEPTH_DECREMENT:
2757                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2758                 break;
2759
2760         case LFUN_DEPTH_INCREMENT:
2761                 enable = changeDepthAllowed(cur, INC_DEPTH);
2762                 break;
2763
2764         case LFUN_APPENDIX:
2765                 // FIXME We really should not allow this to be put, e.g.,
2766                 // in a footnote, or in ERT. But it would make sense in a
2767                 // branch, so I'm not sure what to do.
2768                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2769                 break;
2770
2771         case LFUN_DIALOG_SHOW_NEW_INSET:
2772                 if (cmd.argument() == "bibitem")
2773                         code = BIBITEM_CODE;
2774                 else if (cmd.argument() == "bibtex") {
2775                         code = BIBTEX_CODE;
2776                         // not allowed in description items
2777                         enable = !inDescriptionItem(cur);
2778                 }
2779                 else if (cmd.argument() == "box")
2780                         code = BOX_CODE;
2781                 else if (cmd.argument() == "branch")
2782                         code = BRANCH_CODE;
2783                 else if (cmd.argument() == "citation")
2784                         code = CITE_CODE;
2785                 else if (cmd.argument() == "ert")
2786                         code = ERT_CODE;
2787                 else if (cmd.argument() == "external")
2788                         code = EXTERNAL_CODE;
2789                 else if (cmd.argument() == "float")
2790                         code = FLOAT_CODE;
2791                 else if (cmd.argument() == "graphics")
2792                         code = GRAPHICS_CODE;
2793                 else if (cmd.argument() == "href")
2794                         code = HYPERLINK_CODE;
2795                 else if (cmd.argument() == "include")
2796                         code = INCLUDE_CODE;
2797                 else if (cmd.argument() == "index")
2798                         code = INDEX_CODE;
2799                 else if (cmd.argument() == "index_print")
2800                         code = INDEX_PRINT_CODE;
2801                 else if (cmd.argument() == "listings")
2802                         code = LISTINGS_CODE;
2803                 else if (cmd.argument() == "mathspace")
2804                         code = MATH_HULL_CODE;
2805                 else if (cmd.argument() == "nomenclature")
2806                         code = NOMENCL_CODE;
2807                 else if (cmd.argument() == "nomencl_print")
2808                         code = NOMENCL_PRINT_CODE;
2809                 else if (cmd.argument() == "label")
2810                         code = LABEL_CODE;
2811                 else if (cmd.argument() == "line")
2812                         code = LINE_CODE;
2813                 else if (cmd.argument() == "note")
2814                         code = NOTE_CODE;
2815                 else if (cmd.argument() == "phantom")
2816                         code = PHANTOM_CODE;
2817                 else if (cmd.argument() == "ref")
2818                         code = REF_CODE;
2819                 else if (cmd.argument() == "space")
2820                         code = SPACE_CODE;
2821                 else if (cmd.argument() == "toc")
2822                         code = TOC_CODE;
2823                 else if (cmd.argument() == "vspace")
2824                         code = VSPACE_CODE;
2825                 else if (cmd.argument() == "wrap")
2826                         code = WRAP_CODE;
2827                 break;
2828
2829         case LFUN_ERT_INSERT:
2830                 code = ERT_CODE;
2831                 break;
2832         case LFUN_LISTING_INSERT:
2833                 code = LISTINGS_CODE;
2834                 // not allowed in description items
2835                 enable = !inDescriptionItem(cur);
2836                 break;
2837         case LFUN_FOOTNOTE_INSERT:
2838                 code = FOOT_CODE;
2839                 break;
2840         case LFUN_TABULAR_INSERT:
2841                 code = TABULAR_CODE;
2842                 break;
2843         case LFUN_MARGINALNOTE_INSERT:
2844                 code = MARGIN_CODE;
2845                 break;
2846         case LFUN_FLOAT_INSERT:
2847         case LFUN_FLOAT_WIDE_INSERT:
2848                 // FIXME: If there is a selection, we should check whether there
2849                 // are floats in the selection, but this has performance issues, see
2850                 // LFUN_CHANGE_ACCEPT/REJECT.
2851                 code = FLOAT_CODE;
2852                 if (inDescriptionItem(cur))
2853                         // not allowed in description items
2854                         enable = false;
2855                 else {
2856                         InsetCode const inset_code = cur.inset().lyxCode();
2857
2858                         // algorithm floats cannot be put in another float
2859                         if (to_utf8(cmd.argument()) == "algorithm") {
2860                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2861                                 break;
2862                         }
2863
2864                         // for figures and tables: only allow in another
2865                         // float or wrap if it is of the same type and
2866                         // not a subfloat already
2867                         if(cur.inset().lyxCode() == code) {
2868                                 InsetFloat const & ins =
2869                                         static_cast<InsetFloat const &>(cur.inset());
2870                                 enable = ins.params().type == to_utf8(cmd.argument())
2871                                         && !ins.params().subfloat;
2872                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2873                                 InsetWrap const & ins =
2874                                         static_cast<InsetWrap const &>(cur.inset());
2875                                 enable = ins.params().type == to_utf8(cmd.argument());
2876                         }
2877                 }
2878                 break;
2879         case LFUN_WRAP_INSERT:
2880                 code = WRAP_CODE;
2881                 // not allowed in description items
2882                 enable = !inDescriptionItem(cur);
2883                 break;
2884         case LFUN_FLOAT_LIST_INSERT: {
2885                 code = FLOAT_LIST_CODE;
2886                 // not allowed in description items
2887                 enable = !inDescriptionItem(cur);
2888                 if (enable) {
2889                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2890                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2891                         // make sure we know about such floats
2892                         if (cit == floats.end() ||
2893                                         // and that we know how to generate a list of them
2894                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2895                                 flag.setUnknown(true);
2896                                 // probably not necessary, but...
2897                                 enable = false;
2898                         }
2899                 }
2900                 break;
2901         }
2902         case LFUN_CAPTION_INSERT: {
2903                 code = CAPTION_CODE;
2904                 string arg = cmd.getArg(0);
2905                 bool varia = arg != "Unnumbered"
2906                         && cur.inset().allowsCaptionVariation(arg);
2907                 // not allowed in description items,
2908                 // and in specific insets
2909                 enable = !inDescriptionItem(cur)
2910                         && (varia || arg.empty() || arg == "Standard");
2911                 break;
2912         }
2913         case LFUN_NOTE_INSERT:
2914                 code = NOTE_CODE;
2915                 break;
2916         case LFUN_FLEX_INSERT: {
2917                 code = FLEX_CODE;
2918                 string s = cmd.getArg(0);
2919                 InsetLayout il =
2920                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2921                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2922                     il.lyxtype() != InsetLayout::CUSTOM &&
2923                     il.lyxtype() != InsetLayout::ELEMENT &&
2924                     il.lyxtype ()!= InsetLayout::STANDARD)
2925                         enable = false;
2926                 break;
2927                 }
2928         case LFUN_BOX_INSERT:
2929                 code = BOX_CODE;
2930                 break;
2931         case LFUN_BRANCH_INSERT:
2932                 code = BRANCH_CODE;
2933                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2934                     && cur.buffer()->params().branchlist().empty())
2935                         enable = false;
2936                 break;
2937         case LFUN_IPA_INSERT:
2938                 code = IPA_CODE;
2939                 break;
2940         case LFUN_PHANTOM_INSERT:
2941                 code = PHANTOM_CODE;
2942                 break;
2943         case LFUN_LABEL_INSERT:
2944                 code = LABEL_CODE;
2945                 break;
2946         case LFUN_INFO_INSERT:
2947                 code = INFO_CODE;
2948                 break;
2949         case LFUN_ARGUMENT_INSERT: {
2950                 code = ARG_CODE;
2951                 allow_in_passthru = true;
2952                 string const arg = cmd.getArg(0);
2953                 if (arg.empty()) {
2954                         enable = false;
2955                         break;
2956                 }
2957                 Layout const & lay = cur.paragraph().layout();
2958                 Layout::LaTeXArgMap args = lay.args();
2959                 Layout::LaTeXArgMap::const_iterator const lait =
2960                                 args.find(arg);
2961                 if (lait != args.end()) {
2962                         enable = true;
2963                         pit_type pit = cur.pit();
2964                         pit_type lastpit = cur.pit();
2965                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
2966                                 // In a sequence of "merged" environment layouts, we only allow
2967                                 // non-item arguments once.
2968                                 lastpit = cur.lastpit();
2969                                 // get the first paragraph in sequence with this layout
2970                                 depth_type const current_depth = cur.paragraph().params().depth();
2971                                 while (true) {
2972                                         if (pit == 0)
2973                                                 break;
2974                                         Paragraph cpar = pars_[pit - 1];
2975                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
2976                                                 --pit;
2977                                         else
2978                                                 break;
2979                                 }
2980                         }
2981                         for (; pit <= lastpit; ++pit) {
2982                                 if (pars_[pit].layout() != lay)
2983                                         break;
2984                                 for (auto const & table : pars_[pit].insetList())
2985                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
2986                                                 if (ins->name() == arg) {
2987                                                         // we have this already
2988                                                         enable = false;
2989                                                         break;
2990                                                 }
2991                         }
2992                 } else
2993                         enable = false;
2994                 break;
2995         }
2996         case LFUN_INDEX_INSERT:
2997                 code = INDEX_CODE;
2998                 break;
2999         case LFUN_INDEX_PRINT:
3000                 code = INDEX_PRINT_CODE;
3001                 // not allowed in description items
3002                 enable = !inDescriptionItem(cur);
3003                 break;
3004         case LFUN_NOMENCL_INSERT:
3005                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3006                         enable = false;
3007                         break;
3008                 }
3009                 code = NOMENCL_CODE;
3010                 break;
3011         case LFUN_NOMENCL_PRINT:
3012                 code = NOMENCL_PRINT_CODE;
3013                 // not allowed in description items
3014                 enable = !inDescriptionItem(cur);
3015                 break;
3016         case LFUN_HREF_INSERT:
3017                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3018                         enable = false;
3019                         break;
3020                 }
3021                 code = HYPERLINK_CODE;
3022                 break;
3023         case LFUN_IPAMACRO_INSERT: {
3024                 string const arg = cmd.getArg(0);
3025                 if (arg == "deco")
3026                         code = IPADECO_CODE;
3027                 else
3028                         code = IPACHAR_CODE;
3029                 break;
3030         }
3031         case LFUN_QUOTE_INSERT:
3032                 // always allow this, since we will inset a raw quote
3033                 // if an inset is not allowed.
3034                 allow_in_passthru = true;
3035                 break;
3036         case LFUN_SPECIALCHAR_INSERT:
3037                 code = SPECIALCHAR_CODE;
3038                 break;
3039         case LFUN_SPACE_INSERT:
3040                 // slight hack: we know this is allowed in math mode
3041                 if (cur.inTexted())
3042                         code = SPACE_CODE;
3043                 break;
3044         case LFUN_PREVIEW_INSERT:
3045                 code = PREVIEW_CODE;
3046                 break;
3047         case LFUN_SCRIPT_INSERT:
3048                 code = SCRIPT_CODE;
3049                 break;
3050
3051         case LFUN_MATH_INSERT:
3052         case LFUN_MATH_AMS_MATRIX:
3053         case LFUN_MATH_MATRIX:
3054         case LFUN_MATH_DELIM:
3055         case LFUN_MATH_BIGDELIM:
3056         case LFUN_MATH_DISPLAY:
3057         case LFUN_MATH_MODE:
3058         case LFUN_MATH_MACRO:
3059         case LFUN_MATH_SUBSCRIPT:
3060         case LFUN_MATH_SUPERSCRIPT:
3061                 code = MATH_HULL_CODE;
3062                 break;
3063
3064         case LFUN_REGEXP_MODE:
3065                 code = MATH_HULL_CODE;
3066                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3067                 break;
3068
3069         case LFUN_INSET_MODIFY:
3070                 // We need to disable this, because we may get called for a
3071                 // tabular cell via
3072                 // InsetTabular::getStatus() -> InsetText::getStatus()
3073                 // and we don't handle LFUN_INSET_MODIFY.
3074                 enable = false;
3075                 break;
3076
3077         case LFUN_FONT_EMPH:
3078                 flag.setOnOff(fontinfo.emph() == FONT_ON);
3079                 enable = !cur.paragraph().isPassThru();
3080                 break;
3081
3082         case LFUN_FONT_ITAL:
3083                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3084                 enable = !cur.paragraph().isPassThru();
3085                 break;
3086
3087         case LFUN_FONT_NOUN:
3088                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3089                 enable = !cur.paragraph().isPassThru();
3090                 break;
3091
3092         case LFUN_FONT_BOLD:
3093         case LFUN_FONT_BOLDSYMBOL:
3094                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3095                 enable = !cur.paragraph().isPassThru();
3096                 break;
3097
3098         case LFUN_FONT_SANS:
3099                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3100                 enable = !cur.paragraph().isPassThru();
3101                 break;
3102
3103         case LFUN_FONT_ROMAN:
3104                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3105                 enable = !cur.paragraph().isPassThru();
3106                 break;
3107
3108         case LFUN_FONT_TYPEWRITER:
3109                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3110                 enable = !cur.paragraph().isPassThru();
3111                 break;
3112
3113         case LFUN_CUT:
3114         case LFUN_COPY:
3115                 enable = cur.selection();
3116                 break;
3117
3118         case LFUN_PASTE: {
3119                 if (cmd.argument().empty()) {
3120                         if (theClipboard().isInternal())
3121                                 enable = cap::numberOfSelections() > 0;
3122                         else
3123                                 enable = !theClipboard().empty();
3124                         break;
3125                 }
3126
3127                 // we have an argument
3128                 string const arg = to_utf8(cmd.argument());
3129                 if (isStrUnsignedInt(arg)) {
3130                         // it's a number and therefore means the internal stack
3131                         unsigned int n = convert<unsigned int>(arg);
3132                         enable = cap::numberOfSelections() > n;
3133                         break;
3134                 }
3135
3136                 // explicit text type?
3137                 if (arg == "html") {
3138                         // Do not enable for PlainTextType, since some tidying in the
3139                         // frontend is needed for HTML, which is too unsafe for plain text.
3140                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3141                         break;
3142                 } else if (arg == "latex") {
3143                         // LaTeX is usually not available on the clipboard with
3144                         // the correct MIME type, but in plain text.
3145                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3146                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3147                         break;
3148                 }
3149
3150                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3151                 if (arg == "pdf")
3152                         type = Clipboard::PdfGraphicsType;
3153                 else if (arg == "png")
3154                         type = Clipboard::PngGraphicsType;
3155                 else if (arg == "jpeg")
3156                         type = Clipboard::JpegGraphicsType;
3157                 else if (arg == "linkback")
3158                         type = Clipboard::LinkBackGraphicsType;
3159                 else if (arg == "emf")
3160                         type = Clipboard::EmfGraphicsType;
3161                 else if (arg == "wmf")
3162                         type = Clipboard::WmfGraphicsType;
3163                 else {
3164                         // unknown argument
3165                         LYXERR0("Unrecognized graphics type: " << arg);
3166                         // we don't want to assert if the user just mistyped the LFUN
3167                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3168                         enable = false;
3169                         break;
3170                 }
3171                 enable = theClipboard().hasGraphicsContents(type);
3172                 break;
3173         }
3174
3175         case LFUN_CLIPBOARD_PASTE:
3176         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3177                 enable = !theClipboard().empty();
3178                 break;
3179
3180         case LFUN_PRIMARY_SELECTION_PASTE:
3181                 enable = cur.selection() || !theSelection().empty();
3182                 break;
3183
3184         case LFUN_SELECTION_PASTE:
3185                 enable = cap::selection();
3186                 break;
3187
3188         case LFUN_PARAGRAPH_MOVE_UP:
3189                 enable = cur.pit() > 0 && !cur.selection();
3190                 break;
3191
3192         case LFUN_PARAGRAPH_MOVE_DOWN:
3193                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3194                 break;
3195
3196         case LFUN_CHANGE_ACCEPT:
3197         case LFUN_CHANGE_REJECT:
3198                 if (!cur.selection())
3199                         enable = cur.paragraph().isChanged(cur.pos());
3200                 else {
3201                         // will enable if there is a change in the selection
3202                         enable = false;
3203
3204                         // cheap improvement for efficiency: using cached
3205                         // buffer variable, if there is no change in the
3206                         // document, no need to check further.
3207                         if (!cur.buffer()->areChangesPresent())
3208                                 break;
3209
3210                         for (DocIterator it = cur.selectionBegin(); it < cur.selectionEnd(); it.forwardPar()) {
3211                                 pos_type const beg = it.pos();
3212                                 pos_type end;
3213                                 if (it.paragraph().id() == cur.selectionEnd().paragraph().id())
3214                                         end = cur.selectionEnd().pos();
3215                                 else
3216                                         end = it.paragraph().size();
3217                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3218                                         enable = true;
3219                                         break;
3220                                 }
3221                         }
3222                 }
3223                 break;
3224
3225         case LFUN_OUTLINE_UP:
3226         case LFUN_OUTLINE_DOWN:
3227         case LFUN_OUTLINE_IN:
3228         case LFUN_OUTLINE_OUT:
3229                 // FIXME: LyX is not ready for outlining within inset.
3230                 enable = isMainText()
3231                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3232                 break;
3233
3234         case LFUN_NEWLINE_INSERT:
3235                 // LaTeX restrictions (labels or empty par)
3236                 enable = !cur.paragraph().isPassThru()
3237                         && cur.pos() > cur.paragraph().beginOfBody();
3238                 break;
3239
3240         case LFUN_SEPARATOR_INSERT:
3241                 // Always enabled for now
3242                 enable = true;
3243                 break;
3244
3245         case LFUN_TAB_INSERT:
3246         case LFUN_TAB_DELETE:
3247                 enable = cur.paragraph().isPassThru();
3248                 break;
3249
3250         case LFUN_GRAPHICS_SET_GROUP: {
3251                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3252                 if (!ins)
3253                         enable = false;
3254                 else
3255                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3256                 break;
3257         }
3258
3259         case LFUN_NEWPAGE_INSERT:
3260                 // not allowed in description items
3261                 code = NEWPAGE_CODE;
3262                 enable = !inDescriptionItem(cur);
3263                 break;
3264
3265         case LFUN_DATE_INSERT: {
3266                 string const format = cmd.argument().empty()
3267                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
3268                 enable = support::os::is_valid_strftime(format);
3269                 break;
3270         }
3271
3272         case LFUN_LANGUAGE:
3273                 enable = !cur.paragraph().isPassThru();
3274                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3275                 break;
3276
3277         case LFUN_PARAGRAPH_BREAK:
3278                 enable = inset().allowMultiPar();
3279                 break;
3280
3281         case LFUN_SPELLING_ADD:
3282         case LFUN_SPELLING_IGNORE:
3283         case LFUN_SPELLING_REMOVE:
3284                 enable = theSpellChecker() != NULL;
3285                 if (enable && !cmd.getArg(1).empty()) {
3286                         // validate explicitly given language
3287                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3288                         enable &= lang != NULL;
3289                 }
3290                 break;
3291
3292         case LFUN_LAYOUT:
3293         case LFUN_LAYOUT_TOGGLE: {
3294                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3295                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3296                 docstring const layout = resolveLayout(req_layout, cur);
3297
3298                 enable = !owner_->forcePlainLayout() && !layout.empty();
3299                 flag.setOnOff(isAlreadyLayout(layout, cur));
3300                 break;
3301         }
3302
3303         case LFUN_ENVIRONMENT_SPLIT: {
3304                 if (cmd.argument() == "outer") {
3305                         // check if we have an environment in our nesting hierarchy
3306                         bool res = false;
3307                         depth_type const current_depth = cur.paragraph().params().depth();
3308                         pit_type pit = cur.pit();
3309                         Paragraph cpar = pars_[pit];
3310                         while (true) {
3311                                 if (pit == 0 || cpar.params().depth() == 0)
3312                                         break;
3313                                 --pit;
3314                                 cpar = pars_[pit];
3315                                 if (cpar.params().depth() < current_depth)
3316                                         res = cpar.layout().isEnvironment();
3317                         }
3318                         enable = res;
3319                         break;
3320                 }
3321                 else if (cmd.argument() == "previous") {
3322                         // look if we have an environment in the previous par
3323                         pit_type pit = cur.pit();
3324                         Paragraph cpar = pars_[pit];
3325                         if (pit > 0) {
3326                                 --pit;
3327                                 cpar = pars_[pit];
3328                                 enable = cpar.layout().isEnvironment();
3329                                 break;
3330                         }
3331                         enable = false;
3332                         break;
3333                 }
3334                 else if (cur.paragraph().layout().isEnvironment()) {
3335                         enable = cmd.argument() == "before"
3336                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3337                         break;
3338                 }
3339                 enable = false;
3340                 break;
3341         }
3342
3343         case LFUN_LAYOUT_PARAGRAPH:
3344         case LFUN_PARAGRAPH_PARAMS:
3345         case LFUN_PARAGRAPH_PARAMS_APPLY:
3346         case LFUN_PARAGRAPH_UPDATE:
3347                 enable = owner_->allowParagraphCustomization();
3348                 break;
3349
3350         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3351         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3352         //  that cannot be handled by LaTeX but must be converted according
3353         //  to the definition in lib/unicodesymbols?
3354         case LFUN_ACCENT_ACUTE:
3355         case LFUN_ACCENT_BREVE:
3356         case LFUN_ACCENT_CARON:
3357         case LFUN_ACCENT_CEDILLA:
3358         case LFUN_ACCENT_CIRCLE:
3359         case LFUN_ACCENT_CIRCUMFLEX:
3360         case LFUN_ACCENT_DOT:
3361         case LFUN_ACCENT_GRAVE:
3362         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3363         case LFUN_ACCENT_MACRON:
3364         case LFUN_ACCENT_OGONEK:
3365         case LFUN_ACCENT_TIE:
3366         case LFUN_ACCENT_TILDE:
3367         case LFUN_ACCENT_PERISPOMENI:
3368         case LFUN_ACCENT_UMLAUT:
3369         case LFUN_ACCENT_UNDERBAR:
3370         case LFUN_ACCENT_UNDERDOT:
3371         case LFUN_FONT_DEFAULT:
3372         case LFUN_FONT_FRAK:
3373         case LFUN_FONT_SIZE:
3374         case LFUN_FONT_STATE:
3375         case LFUN_FONT_UNDERLINE:
3376         case LFUN_FONT_STRIKEOUT:
3377         case LFUN_FONT_CROSSOUT:
3378         case LFUN_FONT_UNDERUNDERLINE:
3379         case LFUN_FONT_UNDERWAVE:
3380         case LFUN_TEXTSTYLE_APPLY:
3381         case LFUN_TEXTSTYLE_UPDATE:
3382                 enable = !cur.paragraph().isPassThru();
3383                 break;
3384
3385         case LFUN_WORD_DELETE_FORWARD:
3386         case LFUN_WORD_DELETE_BACKWARD:
3387         case LFUN_LINE_DELETE_FORWARD:
3388         case LFUN_WORD_FORWARD:
3389         case LFUN_WORD_BACKWARD:
3390         case LFUN_WORD_RIGHT:
3391         case LFUN_WORD_LEFT:
3392         case LFUN_CHAR_FORWARD:
3393         case LFUN_CHAR_FORWARD_SELECT:
3394         case LFUN_CHAR_BACKWARD:
3395         case LFUN_CHAR_BACKWARD_SELECT:
3396         case LFUN_CHAR_LEFT:
3397         case LFUN_CHAR_LEFT_SELECT:
3398         case LFUN_CHAR_RIGHT:
3399         case LFUN_CHAR_RIGHT_SELECT:
3400         case LFUN_UP:
3401         case LFUN_UP_SELECT:
3402         case LFUN_DOWN:
3403         case LFUN_DOWN_SELECT:
3404         case LFUN_PARAGRAPH_UP_SELECT:
3405         case LFUN_PARAGRAPH_DOWN_SELECT:
3406         case LFUN_LINE_BEGIN_SELECT:
3407         case LFUN_LINE_END_SELECT:
3408         case LFUN_WORD_FORWARD_SELECT:
3409         case LFUN_WORD_BACKWARD_SELECT:
3410         case LFUN_WORD_RIGHT_SELECT:
3411         case LFUN_WORD_LEFT_SELECT:
3412         case LFUN_WORD_SELECT:
3413         case LFUN_SECTION_SELECT:
3414         case LFUN_BUFFER_BEGIN:
3415         case LFUN_BUFFER_END:
3416         case LFUN_BUFFER_BEGIN_SELECT:
3417         case LFUN_BUFFER_END_SELECT:
3418         case LFUN_INSET_BEGIN:
3419         case LFUN_INSET_END:
3420         case LFUN_INSET_BEGIN_SELECT:
3421         case LFUN_INSET_END_SELECT:
3422         case LFUN_PARAGRAPH_UP:
3423         case LFUN_PARAGRAPH_DOWN:
3424         case LFUN_LINE_BEGIN:
3425         case LFUN_LINE_END:
3426         case LFUN_CHAR_DELETE_FORWARD:
3427         case LFUN_CHAR_DELETE_BACKWARD:
3428         case LFUN_WORD_UPCASE:
3429         case LFUN_WORD_LOWCASE:
3430         case LFUN_WORD_CAPITALIZE:
3431         case LFUN_CHARS_TRANSPOSE:
3432         case LFUN_SERVER_GET_XY:
3433         case LFUN_SERVER_SET_XY:
3434         case LFUN_SERVER_GET_LAYOUT:
3435         case LFUN_SELF_INSERT:
3436         case LFUN_UNICODE_INSERT:
3437         case LFUN_THESAURUS_ENTRY:
3438         case LFUN_ESCAPE:
3439         case LFUN_SERVER_GET_STATISTICS:
3440                 // these are handled in our dispatch()
3441                 enable = true;
3442                 break;
3443
3444         case LFUN_INSET_INSERT: {
3445                 string const type = cmd.getArg(0);
3446                 if (type == "toc") {
3447                         code = TOC_CODE;
3448                         // not allowed in description items
3449                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3450                         enable = !inDescriptionItem(cur);
3451                 } else {
3452                         enable = true;
3453                 }
3454                 break;
3455         }
3456
3457         default:
3458                 return false;
3459         }
3460
3461         if (code != NO_CODE
3462             && (cur.empty()
3463                 || !cur.inset().insetAllowed(code)
3464                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3465                 enable = false;
3466
3467         flag.setEnabled(enable);
3468         return true;
3469 }
3470
3471
3472 void Text::pasteString(Cursor & cur, docstring const & clip,
3473                 bool asParagraphs)
3474 {
3475         if (!clip.empty()) {
3476                 cur.recordUndo();
3477                 if (asParagraphs)
3478                         insertStringAsParagraphs(cur, clip, cur.current_font);
3479                 else
3480                         insertStringAsLines(cur, clip, cur.current_font);
3481         }
3482 }
3483
3484
3485 // FIXME: an item inset would make things much easier.
3486 bool Text::inDescriptionItem(Cursor & cur) const
3487 {
3488         Paragraph & par = cur.paragraph();
3489         pos_type const pos = cur.pos();
3490         pos_type const body_pos = par.beginOfBody();
3491
3492         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3493             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3494                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3495                 return false;
3496
3497         return (pos < body_pos
3498                 || (pos == body_pos
3499                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3500 }
3501
3502 } // namespace lyx