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