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