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