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