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