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