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