]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
fix "make check" with gcc 4.3
[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                 InsetLayout const & ilayout = cur.inset().getLayout(bufparams);
1213                 if (!style.pass_thru && !ilayout.isPassThru()
1214                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1215                         // this avoids a double undo
1216                         // FIXME: should not be needed, ideally
1217                         if (!cur.selection())
1218                                 cur.recordUndo();
1219                         cap::replaceSelection(cur);
1220                         pos = cur.pos();
1221                         char_type c;
1222                         if (pos == 0)
1223                                 c = ' ';
1224                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1225                                 c = ' ';
1226                         else
1227                                 c = par.getChar(pos - 1);
1228                         string arg = to_utf8(cmd.argument());
1229                         cur.insert(new InsetQuotes(bv->buffer(), c, (arg == "single")
1230                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1231                         cur.posForward();
1232                 }
1233                 else
1234                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1235                 break;
1236         }
1237
1238         case LFUN_DATE_INSERT: {
1239                 string const format = cmd.argument().empty()
1240                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1241                 string const time = formatted_time(current_time(), format);
1242                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1243                 break;
1244         }
1245
1246         case LFUN_MOUSE_TRIPLE:
1247                 if (cmd.button() == mouse_button::button1) {
1248                         tm.cursorHome(cur);
1249                         cur.resetAnchor();
1250                         tm.cursorEnd(cur);
1251                         cur.setSelection();
1252                         bv->cursor() = cur;
1253                 }
1254                 break;
1255
1256         case LFUN_MOUSE_DOUBLE:
1257                 if (cmd.button() == mouse_button::button1) {
1258                         selectWord(cur, WHOLE_WORD_STRICT);
1259                         bv->cursor() = cur;
1260                 }
1261                 break;
1262
1263         // Single-click on work area
1264         case LFUN_MOUSE_PRESS:
1265                 // We are not marking a selection with the keyboard in any case.
1266                 cur.bv().cursor().setMark(false);
1267                 switch (cmd.button()) {
1268                 case mouse_button::button1:
1269                         // Set the cursor
1270                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1271                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1272                         break;
1273
1274                 case mouse_button::button2:
1275                         // Middle mouse pasting.
1276                         bv->mouseSetCursor(cur);
1277                         lyx::dispatch(
1278                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1279                                             "selection-paste ; primary-selection-paste paragraph"));
1280                         cur.noUpdate();
1281                         break;
1282
1283                 case mouse_button::button3: {
1284                         Cursor const & bvcur = cur.bv().cursor();
1285                         // Don't do anything if we right-click a
1286                         // selection, a context menu will popup.
1287                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1288                             && cur < bvcur.selectionEnd()) {
1289                                 cur.noUpdate();
1290                                 return;
1291                         }
1292                         if (!bv->mouseSetCursor(cur, false))
1293                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1294                         break;
1295                 }
1296
1297                 default:
1298                         break;
1299                 } // switch (cmd.button())
1300                 break;
1301
1302         case LFUN_MOUSE_MOTION: {
1303                 // Mouse motion with right or middle mouse do nothing for now.
1304                 if (cmd.button() != mouse_button::button1) {
1305                         cur.noUpdate();
1306                         return;
1307                 }
1308                 // ignore motions deeper nested than the real anchor
1309                 Cursor & bvcur = cur.bv().cursor();
1310                 if (!bvcur.anchor_.hasPart(cur)) {
1311                         cur.undispatched();
1312                         break;
1313                 }
1314                 CursorSlice old = bvcur.top();
1315
1316                 int const wh = bv->workHeight();
1317                 int const y = max(0, min(wh - 1, cmd.y));
1318
1319                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1320                 cur.setTargetX(cmd.x);
1321                 if (cmd.y >= wh)
1322                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1323                 else if (cmd.y < 0)
1324                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1325                 // This is to allow jumping over large insets
1326                 if (cur.top() == old) {
1327                         if (cmd.y >= wh)
1328                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1329                         else if (cmd.y < 0)
1330                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1331                 }
1332                 // We continue with our existing selection or start a new one, so don't
1333                 // reset the anchor.
1334                 bvcur.setCursor(cur);
1335                 bvcur.setSelection(true);
1336                 if (cur.top() == old) {
1337                         // We didn't move one iota, so no need to update the screen.
1338                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1339                         //cur.noUpdate();
1340                         return;
1341                 }
1342                 break;
1343         }
1344
1345         case LFUN_MOUSE_RELEASE:
1346                 switch (cmd.button()) {
1347                 case mouse_button::button1:
1348                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1349                         // If there is a new selection, update persistent selection;
1350                         // otherwise, single click does not clear persistent selection
1351                         // buffer.
1352                         if (cur.selection()) {
1353                                 // Finish selection. If double click,
1354                                 // cur is moved to the end of word by
1355                                 // selectWord but bvcur is current
1356                                 // mouse position.
1357                                 cur.bv().cursor().setSelection();
1358                                 // We might have removed an empty but drawn selection
1359                                 // (probably a margin)
1360                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1361                         } else
1362                                 cur.noUpdate();
1363                         // FIXME: We could try to handle drag and drop of selection here.
1364                         return;
1365
1366                 case mouse_button::button2:
1367                         // Middle mouse pasting is handled at mouse press time,
1368                         // see LFUN_MOUSE_PRESS.
1369                         cur.noUpdate();
1370                         return;
1371
1372                 case mouse_button::button3:
1373                         // Cursor was set at LFUN_MOUSE_PRESS time.
1374                         // FIXME: If there is a selection we could try to handle a special
1375                         // drag & drop context menu.
1376                         cur.noUpdate();
1377                         return;
1378
1379                 case mouse_button::none:
1380                 case mouse_button::button4:
1381                 case mouse_button::button5:
1382                         break;
1383                 } // switch (cmd.button())
1384
1385                 break;
1386
1387         case LFUN_SELF_INSERT: {
1388                 if (cmd.argument().empty())
1389                         break;
1390
1391                 // Automatically delete the currently selected
1392                 // text and replace it with what is being
1393                 // typed in now. Depends on lyxrc settings
1394                 // "auto_region_delete", which defaults to
1395                 // true (on).
1396
1397                 if (lyxrc.auto_region_delete && cur.selection())
1398                         cutSelection(cur, false, false);
1399
1400                 cur.clearSelection();
1401
1402                 docstring::const_iterator cit = cmd.argument().begin();
1403                 docstring::const_iterator const end = cmd.argument().end();
1404                 for (; cit != end; ++cit)
1405                         bv->translateAndInsert(*cit, this, cur);
1406
1407                 cur.resetAnchor();
1408                 moveCursor(cur, false);
1409                 bv->bookmarkEditPosition();
1410                 break;
1411         }
1412
1413         case LFUN_HYPERLINK_INSERT: {
1414                 InsetCommandParams p(HYPERLINK_CODE);
1415                 docstring content;
1416                 if (cur.selection()) {
1417                         content = cur.selectionAsString(false);
1418                         cutSelection(cur, true, false);
1419                 }
1420                 p["target"] = (cmd.argument().empty()) ?
1421                         content : cmd.argument();
1422                 string const data = InsetCommand::params2string("href", p);
1423                 if (p["target"].empty()) {
1424                         bv->showDialog("href", data);
1425                 } else {
1426                         FuncRequest fr(LFUN_INSET_INSERT, data);
1427                         dispatch(cur, fr);
1428                 }
1429                 break;
1430         }
1431
1432         case LFUN_LABEL_INSERT: {
1433                 InsetCommandParams p(LABEL_CODE);
1434                 // Try to generate a valid label
1435                 p["name"] = (cmd.argument().empty()) ?
1436                         cur.getPossibleLabel() :
1437                         cmd.argument();
1438                 string const data = InsetCommand::params2string("label", p);
1439
1440                 if (cmd.argument().empty()) {
1441                         bv->showDialog("label", data);
1442                 } else {
1443                         FuncRequest fr(LFUN_INSET_INSERT, data);
1444                         dispatch(cur, fr);
1445                 }
1446                 break;
1447         }
1448
1449         case LFUN_INFO_INSERT: {
1450                 Inset * inset;
1451                 if (cmd.argument().empty() && cur.selection()) {
1452                         // if command argument is empty use current selection as parameter.
1453                         docstring ds = cur.selectionAsString(false);
1454                         cutSelection(cur, true, false);
1455                         FuncRequest cmd0(cmd, ds);
1456                         inset = createInset(cur.bv().buffer(), cmd0);
1457                 } else {
1458                         inset = createInset(cur.bv().buffer(), cmd);
1459                 }
1460                 if (!inset)
1461                         break;
1462                 insertInset(cur, inset);
1463                 cur.posForward();
1464                 break;
1465         }
1466         case LFUN_CAPTION_INSERT:
1467         case LFUN_FOOTNOTE_INSERT:
1468         case LFUN_NOTE_INSERT:
1469         case LFUN_FLEX_INSERT:
1470         case LFUN_BOX_INSERT:
1471         case LFUN_BRANCH_INSERT:
1472         case LFUN_PHANTOM_INSERT:
1473         case LFUN_ERT_INSERT:
1474         case LFUN_LISTING_INSERT:
1475         case LFUN_MARGINALNOTE_INSERT:
1476         case LFUN_OPTIONAL_INSERT:
1477         case LFUN_INDEX_INSERT:
1478                 // Open the inset, and move the current selection
1479                 // inside it.
1480                 doInsertInset(cur, this, cmd, true, true);
1481                 cur.posForward();
1482                 // Some insets are numbered, others are shown in the outline pane so
1483                 // let's update the labels and the toc backend.
1484                 bv->buffer().updateLabels();
1485                 break;
1486
1487         case LFUN_TABULAR_INSERT:
1488                 // if there were no arguments, just open the dialog
1489                 if (doInsertInset(cur, this, cmd, false, true))
1490                         cur.posForward();
1491                 else
1492                         bv->showDialog("tabularcreate");
1493
1494                 break;
1495
1496         case LFUN_FLOAT_INSERT:
1497         case LFUN_FLOAT_WIDE_INSERT:
1498         case LFUN_WRAP_INSERT: {
1499                 // will some text be moved into the inset?
1500                 bool content = cur.selection();
1501
1502                 doInsertInset(cur, this, cmd, true, true);
1503                 cur.posForward();
1504
1505                 // If some text is moved into the inset, doInsertInset 
1506                 // puts the cursor outside the inset. To insert the
1507                 // caption we put it back into the inset.
1508                 if (content)
1509                         cur.backwardPos();
1510
1511                 ParagraphList & pars = cur.text()->paragraphs();
1512
1513                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1514
1515                 // add a separate paragraph for the caption inset
1516                 pars.push_back(Paragraph());
1517                 pars.back().setInsetOwner(&pars[0].inInset());
1518                 pars.back().setPlainOrDefaultLayout(tclass);
1519                 int cap_pit = pars.size() - 1;
1520
1521                 // if an empty inset was created, we create an additional empty
1522                 // paragraph at the bottom so that the user can choose where to put
1523                 // the graphics (or table).
1524                 if (!content) {
1525                         pars.push_back(Paragraph());
1526                         pars.back().setInsetOwner(&pars[0].inInset());
1527                         pars.back().setPlainOrDefaultLayout(tclass);
1528                 }
1529
1530                 // reposition the cursor to the caption
1531                 cur.pit() = cap_pit;
1532                 cur.pos() = 0;
1533                 // FIXME: This Text/Cursor dispatch handling is a mess!
1534                 // We cannot use Cursor::dispatch here it needs access to up to
1535                 // date metrics.
1536                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1537                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1538                 bv->buffer().updateLabels();
1539                 cur.updateFlags(Update::Force);
1540                 // FIXME: When leaving the Float (or Wrap) inset we should
1541                 // delete any empty paragraph left above or below the
1542                 // caption.
1543                 break;
1544         }
1545
1546         case LFUN_NOMENCL_INSERT: {
1547                 InsetCommandParams p(NOMENCL_CODE);
1548                 if (cmd.argument().empty())
1549                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1550                 else
1551                         p["symbol"] = cmd.argument();
1552                 string const data = InsetCommand::params2string("nomenclature", p);
1553                 bv->showDialog("nomenclature", data);
1554                 break;
1555         }
1556
1557         case LFUN_INDEX_PRINT:
1558         case LFUN_NOMENCL_PRINT:
1559         case LFUN_TOC_INSERT:
1560         case LFUN_LINE_INSERT:
1561         case LFUN_NEWPAGE_INSERT:
1562                 // do nothing fancy
1563                 doInsertInset(cur, this, cmd, false, false);
1564                 cur.posForward();
1565                 break;
1566
1567         case LFUN_DEPTH_DECREMENT:
1568                 changeDepth(cur, DEC_DEPTH);
1569                 break;
1570
1571         case LFUN_DEPTH_INCREMENT:
1572                 changeDepth(cur, INC_DEPTH);
1573                 break;
1574
1575         case LFUN_MATH_DISPLAY:
1576                 mathDispatch(cur, cmd, true);
1577                 break;
1578
1579         case LFUN_REGEXP_MODE:
1580                 regexpDispatch(cur, cmd);
1581                 break;
1582
1583         case LFUN_MATH_MODE:
1584                 if (cmd.argument() == "on")
1585                         // don't pass "on" as argument
1586                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1587                 else
1588                         mathDispatch(cur, cmd, false);
1589                 break;
1590
1591         case LFUN_MATH_MACRO:
1592                 if (cmd.argument().empty())
1593                         cur.errorMessage(from_utf8(N_("Missing argument")));
1594                 else {
1595                         string s = to_utf8(cmd.argument());
1596                         string const s1 = token(s, ' ', 1);
1597                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1598                         string const s2 = token(s, ' ', 2);
1599                         MacroType type = MacroTypeNewcommand;
1600                         if (s2 == "def")
1601                                 type = MacroTypeDef;
1602                         MathMacroTemplate * inset = new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type);
1603                         inset->setBuffer(bv->buffer());
1604                         insertInset(cur, inset);
1605
1606                         // enter macro inset and select the name
1607                         cur.push(*inset);
1608                         cur.top().pos() = cur.top().lastpos();
1609                         cur.resetAnchor();
1610                         cur.setSelection(true);
1611                         cur.top().pos() = 0;
1612                 }
1613                 break;
1614
1615         // passthrough hat and underscore outside mathed:
1616         case LFUN_MATH_SUBSCRIPT:
1617                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1618                 break;
1619         case LFUN_MATH_SUPERSCRIPT:
1620                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1621                 break;
1622
1623         case LFUN_MATH_INSERT:
1624         case LFUN_MATH_MATRIX:
1625         case LFUN_MATH_DELIM:
1626         case LFUN_MATH_BIGDELIM: {
1627                 cur.recordUndo();
1628                 cap::replaceSelection(cur);
1629                 cur.insert(new InsetMathHull(hullSimple));
1630                 checkAndActivateInset(cur, true);
1631                 LASSERT(cur.inMathed(), /**/);
1632                 cur.dispatch(cmd);
1633                 break;
1634         }
1635
1636         case LFUN_FONT_EMPH: {
1637                 Font font(ignore_font, ignore_language);
1638                 font.fontInfo().setEmph(FONT_TOGGLE);
1639                 toggleAndShow(cur, this, font);
1640                 break;
1641         }
1642
1643         case LFUN_FONT_ITAL: {
1644                 Font font(ignore_font, ignore_language);
1645                 font.fontInfo().setShape(ITALIC_SHAPE);
1646                 toggleAndShow(cur, this, font);
1647                 break;
1648         }
1649
1650         case LFUN_FONT_BOLD:
1651         case LFUN_FONT_BOLDSYMBOL: {
1652                 Font font(ignore_font, ignore_language);
1653                 font.fontInfo().setSeries(BOLD_SERIES);
1654                 toggleAndShow(cur, this, font);
1655                 break;
1656         }
1657
1658         case LFUN_FONT_NOUN: {
1659                 Font font(ignore_font, ignore_language);
1660                 font.fontInfo().setNoun(FONT_TOGGLE);
1661                 toggleAndShow(cur, this, font);
1662                 break;
1663         }
1664
1665         case LFUN_FONT_TYPEWRITER: {
1666                 Font font(ignore_font, ignore_language);
1667                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1668                 toggleAndShow(cur, this, font);
1669                 break;
1670         }
1671
1672         case LFUN_FONT_SANS: {
1673                 Font font(ignore_font, ignore_language);
1674                 font.fontInfo().setFamily(SANS_FAMILY);
1675                 toggleAndShow(cur, this, font);
1676                 break;
1677         }
1678
1679         case LFUN_FONT_ROMAN: {
1680                 Font font(ignore_font, ignore_language);
1681                 font.fontInfo().setFamily(ROMAN_FAMILY);
1682                 toggleAndShow(cur, this, font);
1683                 break;
1684         }
1685
1686         case LFUN_FONT_DEFAULT: {
1687                 Font font(inherit_font, ignore_language);
1688                 toggleAndShow(cur, this, font);
1689                 break;
1690         }
1691
1692         case LFUN_FONT_UNDERLINE: {
1693                 Font font(ignore_font, ignore_language);
1694                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1695                 toggleAndShow(cur, this, font);
1696                 break;
1697         }
1698
1699         case LFUN_FONT_SIZE: {
1700                 Font font(ignore_font, ignore_language);
1701                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1702                 toggleAndShow(cur, this, font);
1703                 break;
1704         }
1705
1706         case LFUN_LANGUAGE: {
1707                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1708                 if (!lang)
1709                         break;
1710                 Font font(ignore_font, lang);
1711                 toggleAndShow(cur, this, font);
1712                 break;
1713         }
1714
1715         case LFUN_TEXTSTYLE_APPLY:
1716                 toggleAndShow(cur, this, freefont, toggleall);
1717                 cur.message(_("Character set"));
1718                 break;
1719
1720         // Set the freefont using the contents of \param data dispatched from
1721         // the frontends and apply it at the current cursor location.
1722         case LFUN_TEXTSTYLE_UPDATE: {
1723                 Font font;
1724                 bool toggle;
1725                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1726                         freefont = font;
1727                         toggleall = toggle;
1728                         toggleAndShow(cur, this, freefont, toggleall);
1729                         cur.message(_("Character set"));
1730                 } else {
1731                         lyxerr << "Argument not ok";
1732                 }
1733                 break;
1734         }
1735
1736         case LFUN_FINISHED_LEFT:
1737                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1738                 // We're leaving an inset, going left. If the inset is LTR, we're
1739                 // leaving from the front, so we should not move (remain at --- but
1740                 // not in --- the inset). If the inset is RTL, move left, without
1741                 // entering the inset itself; i.e., move to after the inset.
1742                 if (cur.paragraph().getFontSettings(
1743                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1744                         cursorVisLeft(cur, true);
1745                 break;
1746
1747         case LFUN_FINISHED_RIGHT:
1748                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1749                 // We're leaving an inset, going right. If the inset is RTL, we're
1750                 // leaving from the front, so we should not move (remain at --- but
1751                 // not in --- the inset). If the inset is LTR, move right, without
1752                 // entering the inset itself; i.e., move to after the inset.
1753                 if (!cur.paragraph().getFontSettings(
1754                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1755                         cursorVisRight(cur, true);
1756                 break;
1757
1758         case LFUN_FINISHED_BACKWARD:
1759                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1760                 break;
1761
1762         case LFUN_FINISHED_FORWARD:
1763                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1764                 ++cur.pos();
1765                 cur.setCurrentFont();
1766                 break;
1767
1768         case LFUN_LAYOUT_PARAGRAPH: {
1769                 string data;
1770                 params2string(cur.paragraph(), data);
1771                 data = "show\n" + data;
1772                 bv->showDialog("paragraph", data);
1773                 break;
1774         }
1775
1776         case LFUN_PARAGRAPH_UPDATE: {
1777                 string data;
1778                 params2string(cur.paragraph(), data);
1779
1780                 // Will the paragraph accept changes from the dialog?
1781                 bool const accept =
1782                         cur.inset().allowParagraphCustomization(cur.idx());
1783
1784                 data = "update " + convert<string>(accept) + '\n' + data;
1785                 bv->updateDialog("paragraph", data);
1786                 break;
1787         }
1788
1789         case LFUN_ACCENT_UMLAUT:
1790         case LFUN_ACCENT_CIRCUMFLEX:
1791         case LFUN_ACCENT_GRAVE:
1792         case LFUN_ACCENT_ACUTE:
1793         case LFUN_ACCENT_TILDE:
1794         case LFUN_ACCENT_CEDILLA:
1795         case LFUN_ACCENT_MACRON:
1796         case LFUN_ACCENT_DOT:
1797         case LFUN_ACCENT_UNDERDOT:
1798         case LFUN_ACCENT_UNDERBAR:
1799         case LFUN_ACCENT_CARON:
1800         case LFUN_ACCENT_BREVE:
1801         case LFUN_ACCENT_TIE:
1802         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1803         case LFUN_ACCENT_CIRCLE:
1804         case LFUN_ACCENT_OGONEK:
1805                 theLyXFunc().handleKeyFunc(cmd.action);
1806                 if (!cmd.argument().empty())
1807                         // FIXME: Are all these characters encoded in one byte in utf8?
1808                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1809                 break;
1810
1811         case LFUN_FLOAT_LIST_INSERT: {
1812                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1813                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1814                         cur.recordUndo();
1815                         if (cur.selection())
1816                                 cutSelection(cur, true, false);
1817                         breakParagraph(cur);
1818
1819                         if (cur.lastpos() != 0) {
1820                                 cursorBackward(cur);
1821                                 breakParagraph(cur);
1822                         }
1823
1824                         docstring const laystr = cur.inset().usePlainLayout() ?
1825                                 tclass.plainLayoutName() :
1826                                 tclass.defaultLayoutName();
1827                         setLayout(cur, laystr);
1828                         ParagraphParameters p;
1829                         // FIXME If this call were replaced with one to clearParagraphParams(),
1830                         // then we could get rid of this method altogether.
1831                         setParagraphs(cur, p);
1832                         // FIXME This should be simplified when InsetFloatList takes a
1833                         // Buffer in its constructor.
1834                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
1835                         ifl->setBuffer(bv->buffer());
1836                         insertInset(cur, ifl);
1837                         cur.posForward();
1838                 } else {
1839                         lyxerr << "Non-existent float type: "
1840                                << to_utf8(cmd.argument()) << endl;
1841                 }
1842                 break;
1843         }
1844
1845         case LFUN_CHANGE_ACCEPT: {
1846                 acceptOrRejectChanges(cur, ACCEPT);
1847                 break;
1848         }
1849
1850         case LFUN_CHANGE_REJECT: {
1851                 acceptOrRejectChanges(cur, REJECT);
1852                 break;
1853         }
1854
1855         case LFUN_THESAURUS_ENTRY: {
1856                 docstring arg = cmd.argument();
1857                 if (arg.empty()) {
1858                         arg = cur.selectionAsString(false);
1859                         // FIXME
1860                         if (arg.size() > 100 || arg.empty()) {
1861                                 // Get word or selection
1862                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1863                                 arg = cur.selectionAsString(false);
1864                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
1865                         }
1866                 }
1867                 bv->showDialog("thesaurus", to_utf8(arg));
1868                 break;
1869         }
1870
1871         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1872                 // Given data, an encoding of the ParagraphParameters
1873                 // generated in the Paragraph dialog, this function sets
1874                 // the current paragraph, or currently selected paragraphs,
1875                 // appropriately.
1876                 // NOTE: This function overrides all existing settings.
1877                 setParagraphs(cur, cmd.argument());
1878                 cur.message(_("Paragraph layout set"));
1879                 break;
1880         }
1881
1882         case LFUN_PARAGRAPH_PARAMS: {
1883                 // Given data, an encoding of the ParagraphParameters as we'd
1884                 // find them in a LyX file, this function modifies the current paragraph,
1885                 // or currently selected paragraphs.
1886                 // NOTE: This function only modifies, and does not override, existing
1887                 // settings.
1888                 setParagraphs(cur, cmd.argument(), true);
1889                 cur.message(_("Paragraph layout set"));
1890                 break;
1891         }
1892
1893         case LFUN_ESCAPE:
1894                 if (cur.selection()) {
1895                         cur.setSelection(false);
1896                 } else {
1897                         cur.undispatched();
1898                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1899                         // correct, but I'm not 100% sure -- dov, 071019
1900                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1901                 }
1902                 break;
1903
1904         case LFUN_OUTLINE_UP:
1905                 outline(OutlineUp, cur);
1906                 setCursor(cur, cur.pit(), 0);
1907                 cur.buffer()->updateLabels();
1908                 needsUpdate = true;
1909                 break;
1910
1911         case LFUN_OUTLINE_DOWN:
1912                 outline(OutlineDown, cur);
1913                 setCursor(cur, cur.pit(), 0);
1914                 cur.buffer()->updateLabels();
1915                 needsUpdate = true;
1916                 break;
1917
1918         case LFUN_OUTLINE_IN:
1919                 outline(OutlineIn, cur);
1920                 cur.buffer()->updateLabels();
1921                 needsUpdate = true;
1922                 break;
1923
1924         case LFUN_OUTLINE_OUT:
1925                 outline(OutlineOut, cur);
1926                 cur.buffer()->updateLabels();
1927                 needsUpdate = true;
1928                 break;
1929
1930         default:
1931                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
1932                 cur.undispatched();
1933                 break;
1934         }
1935
1936         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1937
1938         // FIXME: The cursor flag is reset two lines below
1939         // so we need to check here if some of the LFUN did touch that.
1940         // for now only Text::erase() and Text::backspace() do that.
1941         // The plan is to verify all the LFUNs and then to remove this
1942         // singleParUpdate boolean altogether.
1943         if (cur.result().update() & Update::Force) {
1944                 singleParUpdate = false;
1945                 needsUpdate = true;
1946         }
1947
1948         // FIXME: the following code should go in favor of fine grained
1949         // update flag treatment.
1950         if (singleParUpdate) {
1951                 // Inserting characters does not change par height in general. So, try
1952                 // to update _only_ this paragraph. BufferView will detect if a full
1953                 // metrics update is needed anyway.
1954                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1955                 return;
1956         }
1957
1958         if (!needsUpdate
1959             && &oldTopSlice.inset() == &cur.inset()
1960             && oldTopSlice.idx() == cur.idx()
1961             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1962             && !cur.selection())
1963                 // FIXME: it would be better if we could just do this
1964                 //
1965                 //if (cur.result().update() != Update::FitCursor)
1966                 //      cur.noUpdate();
1967                 //
1968                 // But some LFUNs do not set Update::FitCursor when needed, so we
1969                 // do it for all. This is not very harmfull as FitCursor will provoke
1970                 // a full redraw only if needed but still, a proper review of all LFUN
1971                 // should be done and this needsUpdate boolean can then be removed.
1972                 cur.updateFlags(Update::FitCursor);
1973         else
1974                 cur.updateFlags(Update::Force | Update::FitCursor);
1975 }
1976
1977
1978 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1979                         FuncStatus & flag) const
1980 {
1981         LASSERT(cur.text() == this, /**/);
1982
1983         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
1984         bool enable = true;
1985         InsetCode code = NO_CODE;
1986
1987         switch (cmd.action) {
1988
1989         case LFUN_DEPTH_DECREMENT:
1990                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1991                 break;
1992
1993         case LFUN_DEPTH_INCREMENT:
1994                 enable = changeDepthAllowed(cur, INC_DEPTH);
1995                 break;
1996
1997         case LFUN_APPENDIX:
1998                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1999                 break;
2000
2001         case LFUN_DIALOG_SHOW_NEW_INSET:
2002                 if (cmd.argument() == "bibitem")
2003                         code = BIBITEM_CODE;
2004                 else if (cmd.argument() == "bibtex")
2005                         code = BIBTEX_CODE;
2006                 else if (cmd.argument() == "box")
2007                         code = BOX_CODE;
2008                 else if (cmd.argument() == "branch")
2009                         code = BRANCH_CODE;
2010                 else if (cmd.argument() == "citation")
2011                         code = CITE_CODE;
2012                 else if (cmd.argument() == "ert")
2013                         code = ERT_CODE;
2014                 else if (cmd.argument() == "external")
2015                         code = EXTERNAL_CODE;
2016                 else if (cmd.argument() == "float")
2017                         code = FLOAT_CODE;
2018                 else if (cmd.argument() == "graphics")
2019                         code = GRAPHICS_CODE;
2020                 else if (cmd.argument() == "href")
2021                         code = HYPERLINK_CODE;
2022                 else if (cmd.argument() == "include")
2023                         code = INCLUDE_CODE;
2024                 else if (cmd.argument() == "index")
2025                         code = INDEX_CODE;
2026                 else if (cmd.argument() == "nomenclature")
2027                         code = NOMENCL_CODE;
2028                 else if (cmd.argument() == "label")
2029                         code = LABEL_CODE;
2030                 else if (cmd.argument() == "note")
2031                         code = NOTE_CODE;
2032                 else if (cmd.argument() == "phantom")
2033                         code = PHANTOM_CODE;
2034                 else if (cmd.argument() == "ref")
2035                         code = REF_CODE;
2036                 else if (cmd.argument() == "space")
2037                         code = SPACE_CODE;
2038                 else if (cmd.argument() == "toc")
2039                         code = TOC_CODE;
2040                 else if (cmd.argument() == "vspace")
2041                         code = VSPACE_CODE;
2042                 else if (cmd.argument() == "wrap")
2043                         code = WRAP_CODE;
2044                 else if (cmd.argument() == "listings")
2045                         code = LISTINGS_CODE;
2046                 break;
2047
2048         case LFUN_ERT_INSERT:
2049                 code = ERT_CODE;
2050                 break;
2051         case LFUN_LISTING_INSERT:
2052                 code = LISTINGS_CODE;
2053                 // not allowed in description items
2054                 enable = !inDescriptionItem(cur);
2055                 break;
2056         case LFUN_FOOTNOTE_INSERT:
2057                 code = FOOT_CODE;
2058                 break;
2059         case LFUN_TABULAR_INSERT:
2060                 code = TABULAR_CODE;
2061                 break;
2062         case LFUN_MARGINALNOTE_INSERT:
2063                 code = MARGIN_CODE;
2064                 break;
2065         case LFUN_FLOAT_INSERT:
2066         case LFUN_FLOAT_WIDE_INSERT:
2067                 code = FLOAT_CODE;
2068                 // not allowed in description items
2069                 enable = !inDescriptionItem(cur);
2070                 break;
2071         case LFUN_WRAP_INSERT:
2072                 code = WRAP_CODE;
2073                 // not allowed in description items
2074                 enable = !inDescriptionItem(cur);
2075                 break;
2076         case LFUN_FLOAT_LIST_INSERT:
2077                 code = FLOAT_LIST_CODE;
2078                 break;
2079         case LFUN_CAPTION_INSERT:
2080                 code = CAPTION_CODE;
2081                 // not allowed in description items
2082                 enable = !inDescriptionItem(cur);
2083                 break;
2084         case LFUN_NOTE_INSERT:
2085                 code = NOTE_CODE;
2086                 // in commands (sections etc.) and description items,
2087                 // only Notes are allowed
2088                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2089                           (!cur.paragraph().layout().isCommand()
2090                            && !inDescriptionItem(cur)));
2091                 break;
2092         case LFUN_FLEX_INSERT: {
2093                 code = FLEX_CODE;
2094                 string s = cmd.getArg(0);
2095                 InsetLayout il =
2096                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2097                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2098                     il.lyxtype() != InsetLayout::CUSTOM &&
2099                     il.lyxtype() != InsetLayout::ELEMENT &&
2100                     il.lyxtype ()!= InsetLayout::STANDARD)
2101                         enable = false;
2102                 break;
2103                 }
2104         case LFUN_BOX_INSERT:
2105                 code = BOX_CODE;
2106                 break;
2107         case LFUN_BRANCH_INSERT:
2108                 code = BRANCH_CODE;
2109                 if (cur.buffer()->masterBuffer()->params().branchlist().empty())
2110                         enable = false;
2111                 break;
2112         case LFUN_PHANTOM_INSERT:
2113                 code = PHANTOM_CODE;
2114                 break;
2115         case LFUN_LABEL_INSERT:
2116                 code = LABEL_CODE;
2117                 break;
2118         case LFUN_INFO_INSERT:
2119                 code = INFO_CODE;
2120                 break;
2121         case LFUN_OPTIONAL_INSERT:
2122                 code = OPTARG_CODE;
2123                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2124                         < cur.paragraph().layout().optionalargs;
2125                 break;
2126         case LFUN_INDEX_INSERT:
2127                 code = INDEX_CODE;
2128                 break;
2129         case LFUN_INDEX_PRINT:
2130                 code = INDEX_PRINT_CODE;
2131                 break;
2132         case LFUN_NOMENCL_INSERT:
2133                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2134                         enable = false;
2135                         break;
2136                 }
2137                 code = NOMENCL_CODE;
2138                 break;
2139         case LFUN_NOMENCL_PRINT:
2140                 code = NOMENCL_PRINT_CODE;
2141                 break;
2142         case LFUN_TOC_INSERT:
2143                 code = TOC_CODE;
2144                 break;
2145         case LFUN_HYPERLINK_INSERT:
2146                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2147                         enable = false;
2148                         break;
2149                 }
2150                 code = HYPERLINK_CODE;
2151                 break;
2152         case LFUN_QUOTE_INSERT:
2153                 // always allow this, since we will inset a raw quote
2154                 // if an inset is not allowed.
2155                 break;
2156         case LFUN_SPECIALCHAR_INSERT:
2157                 code = SPECIALCHAR_CODE;
2158                 break;
2159         case LFUN_SPACE_INSERT:
2160                 // slight hack: we know this is allowed in math mode
2161                 if (cur.inTexted())
2162                         code = SPACE_CODE;
2163                 break;
2164
2165         case LFUN_INSET_MODIFY:
2166                 // We need to disable this, because we may get called for a
2167                 // tabular cell via
2168                 // InsetTabular::getStatus() -> InsetText::getStatus()
2169                 // and we don't handle LFUN_INSET_MODIFY.
2170                 enable = false;
2171                 break;
2172
2173         case LFUN_FONT_EMPH:
2174                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2175                 break;
2176
2177         case LFUN_FONT_ITAL:
2178                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2179                 break;
2180
2181         case LFUN_FONT_NOUN:
2182                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2183                 break;
2184
2185         case LFUN_FONT_BOLD:
2186         case LFUN_FONT_BOLDSYMBOL:
2187                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2188                 break;
2189
2190         case LFUN_FONT_SANS:
2191                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2192                 break;
2193
2194         case LFUN_FONT_ROMAN:
2195                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2196                 break;
2197
2198         case LFUN_FONT_TYPEWRITER:
2199                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2200                 break;
2201
2202         case LFUN_CUT:
2203         case LFUN_COPY:
2204                 enable = cur.selection();
2205                 break;
2206
2207         case LFUN_PASTE: {
2208                 if (cmd.argument().empty()) {
2209                         if (theClipboard().isInternal())
2210                                 enable = cap::numberOfSelections() > 0;
2211                         else
2212                                 enable = !theClipboard().empty();
2213                         break;
2214                 }
2215
2216                 // we have an argument
2217                 string const arg = to_utf8(cmd.argument());
2218                 if (isStrUnsignedInt(arg)) {
2219                         // it's a number and therefore means the internal stack
2220                         unsigned int n = convert<unsigned int>(arg);
2221                         enable = cap::numberOfSelections() > n;
2222                         break;
2223                 }
2224
2225                 // explicit graphics type?
2226                 if ((arg == "pdf" && theClipboard().hasGraphicsContents(Clipboard::PdfGraphicsType))
2227                     || (arg == "png" && theClipboard().hasGraphicsContents(Clipboard::PngGraphicsType))
2228                     || (arg == "jpeg" && theClipboard().hasGraphicsContents(Clipboard::JpegGraphicsType))
2229                     || (arg == "linkback" && theClipboard().hasGraphicsContents(Clipboard::LinkBackGraphicsType))) {
2230                         enable = true;
2231                         break;
2232                 }
2233
2234                 // unknown argument
2235                 enable = false;
2236                 break;
2237          }
2238
2239         case LFUN_CLIPBOARD_PASTE:
2240                 enable = !theClipboard().empty();
2241                 break;
2242
2243         case LFUN_PRIMARY_SELECTION_PASTE:
2244                 enable = cur.selection() || !theSelection().empty();
2245                 break;
2246
2247         case LFUN_SELECTION_PASTE:
2248                 enable = cap::selection();
2249                 break;
2250
2251         case LFUN_PARAGRAPH_MOVE_UP:
2252                 enable = cur.pit() > 0 && !cur.selection();
2253                 break;
2254
2255         case LFUN_PARAGRAPH_MOVE_DOWN:
2256                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2257                 break;
2258
2259         case LFUN_INSET_DISSOLVE:
2260                 if (!cmd.argument().empty()) {
2261                         InsetLayout const & il = cur.inset().getLayout(cur.buffer()->params());
2262                         InsetLayout::InsetLyXType const type = 
2263                                         translateLyXType(to_utf8(cmd.argument()));
2264                         enable = cur.inset().lyxCode() == FLEX_CODE
2265                                  && il.lyxtype() == type;
2266                 } else {
2267                         enable = ((!isMainText(cur.bv().buffer())
2268                                       && cur.inset().nargs() == 1)
2269                                   || (cur.nextInset()
2270                                       && cur.nextInset()->nargs() == 1));
2271                 }
2272                 break;
2273
2274         case LFUN_CHANGE_ACCEPT:
2275         case LFUN_CHANGE_REJECT:
2276                 // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2277                 // In principle, these LFUNs should only be enabled if there
2278                 // is a change at the current position/in the current selection.
2279                 // However, without proper optimizations, this will inevitably
2280                 // result in unacceptable performance - just imagine a user who
2281                 // wants to select the complete content of a long document.
2282                 enable = true;
2283                 break;
2284
2285         case LFUN_OUTLINE_UP:
2286         case LFUN_OUTLINE_DOWN:
2287         case LFUN_OUTLINE_IN:
2288         case LFUN_OUTLINE_OUT:
2289                 // FIXME: LyX is not ready for outlining within inset.
2290                 enable = isMainText(cur.bv().buffer())
2291                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2292                 break;
2293
2294         case LFUN_NEWLINE_INSERT:
2295                 // LaTeX restrictions (labels or empty par)
2296                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2297                 break;
2298
2299         case LFUN_SET_GRAPHICS_GROUP: {
2300                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2301                 if (!ins)
2302                         enable = false;
2303                 else
2304                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2305                 break;
2306         }
2307
2308         case LFUN_NEWPAGE_INSERT:
2309                 // not allowed in description items
2310                 enable = !inDescriptionItem(cur);
2311                 break;
2312
2313         case LFUN_MATH_INSERT:
2314         case LFUN_MATH_MATRIX:
2315         case LFUN_MATH_DELIM:
2316         case LFUN_MATH_BIGDELIM:
2317                 // not allowed in ERT, for example.
2318                 enable = cur.inset().insetAllowed(MATH_CODE);
2319                 break;
2320
2321         case LFUN_WORD_DELETE_FORWARD:
2322         case LFUN_WORD_DELETE_BACKWARD:
2323         case LFUN_LINE_DELETE:
2324         case LFUN_WORD_FORWARD:
2325         case LFUN_WORD_BACKWARD:
2326         case LFUN_WORD_RIGHT:
2327         case LFUN_WORD_LEFT:
2328         case LFUN_CHAR_FORWARD:
2329         case LFUN_CHAR_FORWARD_SELECT:
2330         case LFUN_CHAR_BACKWARD:
2331         case LFUN_CHAR_BACKWARD_SELECT:
2332         case LFUN_CHAR_LEFT:
2333         case LFUN_CHAR_LEFT_SELECT:
2334         case LFUN_CHAR_RIGHT:
2335         case LFUN_CHAR_RIGHT_SELECT:
2336         case LFUN_UP:
2337         case LFUN_UP_SELECT:
2338         case LFUN_DOWN:
2339         case LFUN_DOWN_SELECT:
2340         case LFUN_PARAGRAPH_UP_SELECT:
2341         case LFUN_PARAGRAPH_DOWN_SELECT:
2342         case LFUN_LINE_BEGIN_SELECT:
2343         case LFUN_LINE_END_SELECT:
2344         case LFUN_WORD_FORWARD_SELECT:
2345         case LFUN_WORD_BACKWARD_SELECT:
2346         case LFUN_WORD_RIGHT_SELECT:
2347         case LFUN_WORD_LEFT_SELECT:
2348         case LFUN_WORD_SELECT:
2349         case LFUN_PARAGRAPH_UP:
2350         case LFUN_PARAGRAPH_DOWN:
2351         case LFUN_LINE_BEGIN:
2352         case LFUN_LINE_END:
2353         case LFUN_CHAR_DELETE_FORWARD:
2354         case LFUN_CHAR_DELETE_BACKWARD:
2355         case LFUN_BREAK_PARAGRAPH:
2356         case LFUN_PARAGRAPH_SPACING:
2357         case LFUN_INSET_INSERT:
2358         case LFUN_WORD_UPCASE:
2359         case LFUN_WORD_LOWCASE:
2360         case LFUN_WORD_CAPITALIZE:
2361         case LFUN_CHARS_TRANSPOSE:
2362         case LFUN_SERVER_GET_XY:
2363         case LFUN_SERVER_SET_XY:
2364         case LFUN_SERVER_GET_LAYOUT:
2365         case LFUN_LAYOUT:
2366         case LFUN_DATE_INSERT:
2367         case LFUN_SELF_INSERT:
2368         case LFUN_LINE_INSERT:
2369         case LFUN_MATH_DISPLAY:
2370         case LFUN_MATH_MODE:
2371         case LFUN_MATH_MACRO:
2372         case LFUN_MATH_SUBSCRIPT:
2373         case LFUN_MATH_SUPERSCRIPT:
2374         case LFUN_FONT_DEFAULT:
2375         case LFUN_FONT_UNDERLINE:
2376         case LFUN_FONT_SIZE:
2377         case LFUN_LANGUAGE:
2378         case LFUN_TEXTSTYLE_APPLY:
2379         case LFUN_TEXTSTYLE_UPDATE:
2380         case LFUN_LAYOUT_PARAGRAPH:
2381         case LFUN_PARAGRAPH_UPDATE:
2382         case LFUN_ACCENT_UMLAUT:
2383         case LFUN_ACCENT_CIRCUMFLEX:
2384         case LFUN_ACCENT_GRAVE:
2385         case LFUN_ACCENT_ACUTE:
2386         case LFUN_ACCENT_TILDE:
2387         case LFUN_ACCENT_CEDILLA:
2388         case LFUN_ACCENT_MACRON:
2389         case LFUN_ACCENT_DOT:
2390         case LFUN_ACCENT_UNDERDOT:
2391         case LFUN_ACCENT_UNDERBAR:
2392         case LFUN_ACCENT_CARON:
2393         case LFUN_ACCENT_BREVE:
2394         case LFUN_ACCENT_TIE:
2395         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2396         case LFUN_ACCENT_CIRCLE:
2397         case LFUN_ACCENT_OGONEK:
2398         case LFUN_THESAURUS_ENTRY:
2399         case LFUN_PARAGRAPH_PARAMS_APPLY:
2400         case LFUN_PARAGRAPH_PARAMS:
2401         case LFUN_ESCAPE:
2402         case LFUN_BUFFER_BEGIN:
2403         case LFUN_BUFFER_END:
2404         case LFUN_BUFFER_BEGIN_SELECT:
2405         case LFUN_BUFFER_END_SELECT:
2406         case LFUN_INSET_BEGIN:
2407         case LFUN_INSET_END:
2408         case LFUN_INSET_BEGIN_SELECT:
2409         case LFUN_INSET_END_SELECT:
2410         case LFUN_UNICODE_INSERT:
2411                 // these are handled in our dispatch()
2412                 enable = true;
2413                 break;
2414
2415         default:
2416                 return false;
2417         }
2418
2419         if (code != NO_CODE
2420             && (cur.empty() || !cur.inset().insetAllowed(code)))
2421                 enable = false;
2422
2423         flag.setEnabled(enable);
2424         return true;
2425 }
2426
2427
2428 void Text::pasteString(Cursor & cur, docstring const & clip,
2429                 bool asParagraphs)
2430 {
2431         cur.clearSelection();
2432         if (!clip.empty()) {
2433                 cur.recordUndo();
2434                 if (asParagraphs)
2435                         insertStringAsParagraphs(cur, clip);
2436                 else
2437                         insertStringAsLines(cur, clip);
2438         }
2439 }
2440
2441
2442 // FIXME: an item inset would make things much easier.
2443 bool Text::inDescriptionItem(Cursor & cur) const
2444 {
2445         Paragraph & par = cur.paragraph();
2446         pos_type const pos = cur.pos();
2447         pos_type const body_pos = par.beginOfBody();
2448
2449         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2450             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2451                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2452                 return false;
2453
2454         return (pos < body_pos
2455                 || (pos == body_pos
2456                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2457 }
2458
2459 } // namespace lyx