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