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