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