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