]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Prevent warning when pressing OKAY while the dialog is in AUTOAPPLY_INITIAL state...
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyXFunc.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "VSpace.h"
49
50 #include "frontends/Application.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/LyXView.h"
53 #include "frontends/Selection.h"
54 #include "frontends/WorkArea.h"
55
56 #include "insets/InsetCollapsable.h"
57 #include "insets/InsetCommand.h"
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetFloatList.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetGraphicsParams.h"
62 #include "insets/InsetNewline.h"
63 #include "insets/InsetQuotes.h"
64 #include "insets/InsetSpecialChar.h"
65 #include "insets/InsetText.h"
66
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/gettext.h"
70 #include "support/lstrings.h"
71 #include "support/lyxtime.h"
72 #include "support/os.h"
73
74 #include "mathed/InsetMathHull.h"
75 #include "mathed/MathMacroTemplate.h"
76
77 #include <boost/next_prior.hpp>
78
79 #include <clocale>
80 #include <sstream>
81
82 using namespace std;
83 using namespace lyx::support;
84
85 namespace lyx {
86
87 using cap::copySelection;
88 using cap::cutSelection;
89 using cap::pasteFromStack;
90 using cap::pasteClipboardText;
91 using cap::pasteClipboardGraphics;
92 using cap::replaceSelection;
93 using cap::grabAndEraseSelection;
94 using cap::selClearOrDel;
95
96 // globals...
97 static Font freefont(ignore_font, ignore_language);
98 static bool toggleall = false;
99
100 static void toggleAndShow(Cursor & cur, Text * text,
101         Font const & font, bool toggleall = true)
102 {
103         text->toggleFree(cur, font, toggleall);
104
105         if (font.language() != ignore_language ||
106             font.fontInfo().number() != FONT_IGNORE) {
107                 TextMetrics const & tm = cur.bv().textMetrics(text);
108                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
109                                                        cur.real_current_font))
110                         text->setCursor(cur, cur.pit(), cur.pos(),
111                                         false, !cur.boundary());
112         }
113 }
114
115
116 static void moveCursor(Cursor & cur, bool selecting)
117 {
118         if (selecting || cur.mark())
119                 cur.setSelection();
120 }
121
122
123 static void finishChange(Cursor & cur, bool selecting)
124 {
125         cur.finishUndo();
126         moveCursor(cur, selecting);
127 }
128
129
130 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
131 {
132         cur.recordUndo();
133         docstring sel = cur.selectionAsString(false);
134
135         // It may happen that sel is empty but there is a selection
136         replaceSelection(cur);
137
138         // Is this a valid formula?
139         bool valid = true;
140
141         if (sel.empty()) {
142 #ifdef ENABLE_ASSERTIONS
143                 const int old_pos = cur.pos();
144 #endif
145                 cur.insert(new InsetMathHull(hullSimple));
146 #ifdef ENABLE_ASSERTIONS
147                 LASSERT(old_pos == cur.pos(), /**/);
148 #endif
149                 cur.nextInset()->edit(cur, true);
150                 // don't do that also for LFUN_MATH_MODE
151                 // unless you want end up with always changing
152                 // to mathrm when opening an inlined inset --
153                 // I really hate "LyXfunc overloading"...
154                 if (display)
155                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
156                 // Avoid an unnecessary undo step if cmd.argument
157                 // is empty
158                 if (!cmd.argument().empty())
159                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
160                                                  cmd.argument()));
161         } else {
162                 // create a macro if we see "\\newcommand"
163                 // somewhere, and an ordinary formula
164                 // otherwise
165                 if (sel.find(from_ascii("\\newcommand")) == string::npos
166                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
167                                 && sel.find(from_ascii("\\def")) == string::npos)
168                 {
169                         InsetMathHull * formula = new InsetMathHull;
170                         string const selstr = to_utf8(sel);
171                         istringstream is(selstr);
172                         Lexer lex;
173                         lex.setStream(is);
174                         if (!formula->readQuiet(lex)) {
175                                 // No valid formula, let's try with delims
176                                 is.str("$" + selstr + "$");
177                                 lex.setStream(is);
178                                 if (!formula->readQuiet(lex)) {
179                                         // Still not valid, leave it as is
180                                         valid = false;
181                                         delete formula;
182                                         cur.insert(sel);
183                                 } else
184                                         cur.insert(formula);
185                         } else
186                                 cur.insert(formula);
187                 } else {
188                         cur.insert(new MathMacroTemplate(sel));
189                 }
190         }
191         if (valid)
192                 cur.message(from_utf8(N_("Math editor mode")));
193         else
194                 cur.message(from_utf8(N_("No valid math formula")));
195 }
196
197
198 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
199 {
200         BOOST_ASSERT(cmd.action == LFUN_REGEXP_MODE);
201         if (cur.inRegexped()) {
202                 cur.message(_("Already in regexp mode"));
203                 return;
204         }
205         cur.recordUndo();
206         docstring const save_selection = grabAndEraseSelection(cur);
207         selClearOrDel(cur);
208         // replaceSelection(cur);
209
210         cur.insert(new InsetMathHull(hullRegexp));
211         cur.nextInset()->edit(cur, true);
212         cur.niceInsert(save_selection);
213
214         cur.message(_("Regexp editor mode"));
215 }
216
217
218 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
219 {
220         cur.recordUndo();
221         cap::replaceSelection(cur);
222         cur.insert(new InsetSpecialChar(kind));
223         cur.posForward();
224 }
225
226
227 static bool doInsertInset(Cursor & cur, Text * text,
228         FuncRequest const & cmd, bool edit, bool pastesel)
229 {
230         Buffer & buffer = cur.bv().buffer();
231         BufferParams const & bparams = buffer.params();
232         Inset * inset = createInset(buffer, cmd);
233         if (!inset)
234                 return false;
235
236         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 if (arg == "emf")
1050                                 type = Clipboard::EmfGraphicsType;
1051                         else if (arg == "wmf")
1052                                 type = Clipboard::WmfGraphicsType;
1053
1054                         else
1055                                 LASSERT(false, /**/);
1056
1057                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1058                 }
1059
1060                 bv->buffer().errors("Paste");
1061                 cur.clearSelection(); // bug 393
1062                 cur.finishUndo();
1063                 break;
1064         }
1065
1066         case LFUN_CUT:
1067                 cutSelection(cur, true, true);
1068                 cur.message(_("Cut"));
1069                 break;
1070
1071         case LFUN_COPY:
1072                 copySelection(cur);
1073                 cur.message(_("Copy"));
1074                 break;
1075
1076         case LFUN_SERVER_GET_XY:
1077                 cur.message(from_utf8(
1078                         convert<string>(tm.cursorX(cur.top(), cur.boundary()))
1079                         + ' ' + convert<string>(tm.cursorY(cur.top(), cur.boundary()))));
1080                 break;
1081
1082         case LFUN_SERVER_SET_XY: {
1083                 int x = 0;
1084                 int y = 0;
1085                 istringstream is(to_utf8(cmd.argument()));
1086                 is >> x >> y;
1087                 if (!is)
1088                         lyxerr << "SETXY: Could not parse coordinates in '"
1089                                << to_utf8(cmd.argument()) << endl;
1090                 else
1091                         tm.setCursorFromCoordinates(cur, x, y);
1092                 break;
1093         }
1094
1095         case LFUN_SERVER_GET_LAYOUT:
1096                 cur.message(cur.paragraph().layout().name());
1097                 break;
1098
1099         case LFUN_LAYOUT: {
1100                 docstring layout = cmd.argument();
1101                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1102
1103                 Paragraph const & para = cur.paragraph();
1104                 docstring const old_layout = para.layout().name();
1105                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1106
1107                 if (layout.empty())
1108                         layout = tclass.defaultLayoutName();
1109
1110                 if (para.forcePlainLayout())
1111                         // in this case only the empty layout is allowed
1112                         layout = tclass.plainLayoutName();
1113                 else if (para.usePlainLayout()) {
1114                         // in this case, default layout maps to empty layout
1115                         if (layout == tclass.defaultLayoutName())
1116                                 layout = tclass.plainLayoutName();
1117                 } else {
1118                         // otherwise, the empty layout maps to the default
1119                         if (layout == tclass.plainLayoutName())
1120                                 layout = tclass.defaultLayoutName();
1121                 }
1122
1123                 bool hasLayout = tclass.hasLayout(layout);
1124
1125                 // If the entry is obsolete, use the new one instead.
1126                 if (hasLayout) {
1127                         docstring const & obs = tclass[layout].obsoleted_by();
1128                         if (!obs.empty())
1129                                 layout = obs;
1130                 }
1131
1132                 if (!hasLayout) {
1133                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1134                                 from_utf8(N_(" not known")));
1135                         break;
1136                 }
1137
1138                 bool change_layout = (old_layout != layout);
1139
1140                 if (!change_layout && cur.selection() &&
1141                         cur.selBegin().pit() != cur.selEnd().pit())
1142                 {
1143                         pit_type spit = cur.selBegin().pit();
1144                         pit_type epit = cur.selEnd().pit() + 1;
1145                         while (spit != epit) {
1146                                 if (pars_[spit].layout().name() != old_layout) {
1147                                         change_layout = true;
1148                                         break;
1149                                 }
1150                                 ++spit;
1151                         }
1152                 }
1153
1154                 if (change_layout)
1155                         setLayout(cur, layout);
1156
1157                 break;
1158         }
1159
1160         case LFUN_CLIPBOARD_PASTE:
1161                 cur.clearSelection();
1162                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1163                                cmd.argument() == "paragraph");
1164                 bv->buffer().errors("Paste");
1165                 break;
1166
1167         case LFUN_PRIMARY_SELECTION_PASTE:
1168                 pasteString(cur, theSelection().get(),
1169                             cmd.argument() == "paragraph");
1170                 break;
1171
1172         case LFUN_SELECTION_PASTE:
1173                 // Copy the selection buffer to the clipboard stack,
1174                 // because we want it to appear in the "Edit->Paste
1175                 // recent" menu.
1176                 cap::copySelectionToStack();
1177                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1178                 bv->buffer().errors("Paste");
1179                 break;
1180
1181         case LFUN_UNICODE_INSERT: {
1182                 if (cmd.argument().empty())
1183                         break;
1184                 docstring hexstring = cmd.argument();
1185                 if (isHex(hexstring)) {
1186                         char_type c = hexToInt(hexstring);
1187                         if (c >= 32 && c < 0x10ffff) {
1188                                 lyxerr << "Inserting c: " << c << endl;
1189                                 docstring s = docstring(1, c);
1190                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1191                         }
1192                 }
1193                 break;
1194         }
1195
1196         case LFUN_QUOTE_INSERT: {
1197                 Paragraph & par = cur.paragraph();
1198                 pos_type pos = cur.pos();
1199                 BufferParams const & bufparams = bv->buffer().params();
1200                 Layout const & style = par.layout();
1201                 InsetLayout const & ilayout = cur.inset().getLayout(bufparams);
1202                 if (!style.pass_thru && !ilayout.isPassThru()
1203                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1204                         // this avoids a double undo
1205                         // FIXME: should not be needed, ideally
1206                         if (!cur.selection())
1207                                 cur.recordUndo();
1208                         cap::replaceSelection(cur);
1209                         pos = cur.pos();
1210                         char_type c;
1211                         if (pos == 0)
1212                                 c = ' ';
1213                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1214                                 c = ' ';
1215                         else
1216                                 c = par.getChar(pos - 1);
1217                         string arg = to_utf8(cmd.argument());
1218                         cur.insert(new InsetQuotes(bv->buffer(), c, (arg == "single")
1219                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1220                         cur.posForward();
1221                 }
1222                 else
1223                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1224                 break;
1225         }
1226
1227         case LFUN_DATE_INSERT: {
1228                 string const format = cmd.argument().empty()
1229                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1230                 string const time = formatted_time(current_time(), format);
1231                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1232                 break;
1233         }
1234
1235         case LFUN_MOUSE_TRIPLE:
1236                 if (cmd.button() == mouse_button::button1) {
1237                         tm.cursorHome(cur);
1238                         cur.resetAnchor();
1239                         tm.cursorEnd(cur);
1240                         cur.setSelection();
1241                         bv->cursor() = cur;
1242                 }
1243                 break;
1244
1245         case LFUN_MOUSE_DOUBLE:
1246                 if (cmd.button() == mouse_button::button1) {
1247                         selectWord(cur, WHOLE_WORD_STRICT);
1248                         bv->cursor() = cur;
1249                 }
1250                 break;
1251
1252         // Single-click on work area
1253         case LFUN_MOUSE_PRESS:
1254                 // We are not marking a selection with the keyboard in any case.
1255                 cur.bv().cursor().setMark(false);
1256                 switch (cmd.button()) {
1257                 case mouse_button::button1:
1258                         // Set the cursor
1259                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1260                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1261                         break;
1262
1263                 case mouse_button::button2:
1264                         // Middle mouse pasting.
1265                         bv->mouseSetCursor(cur);
1266                         lyx::dispatch(
1267                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1268                                             "selection-paste ; primary-selection-paste paragraph"));
1269                         cur.noUpdate();
1270                         break;
1271
1272                 case mouse_button::button3: {
1273                         Cursor const & bvcur = cur.bv().cursor();
1274                         // Don't do anything if we right-click a
1275                         // selection, a context menu will popup.
1276                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1277                             && cur < bvcur.selectionEnd()) {
1278                                 cur.noUpdate();
1279                                 return;
1280                         }
1281                         if (!bv->mouseSetCursor(cur, false))
1282                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1283                         break;
1284                 }
1285
1286                 default:
1287                         break;
1288                 } // switch (cmd.button())
1289                 break;
1290
1291         case LFUN_MOUSE_MOTION: {
1292                 // Mouse motion with right or middle mouse do nothing for now.
1293                 if (cmd.button() != mouse_button::button1) {
1294                         cur.noUpdate();
1295                         return;
1296                 }
1297                 // ignore motions deeper nested than the real anchor
1298                 Cursor & bvcur = cur.bv().cursor();
1299                 if (!bvcur.anchor_.hasPart(cur)) {
1300                         cur.undispatched();
1301                         break;
1302                 }
1303                 CursorSlice old = bvcur.top();
1304
1305                 int const wh = bv->workHeight();
1306                 int const y = max(0, min(wh - 1, cmd.y));
1307
1308                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1309                 cur.setTargetX(cmd.x);
1310                 if (cmd.y >= wh)
1311                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1312                 else if (cmd.y < 0)
1313                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1314                 // This is to allow jumping over large insets
1315                 if (cur.top() == old) {
1316                         if (cmd.y >= wh)
1317                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1318                         else if (cmd.y < 0)
1319                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1320                 }
1321                 // We continue with our existing selection or start a new one, so don't
1322                 // reset the anchor.
1323                 bvcur.setCursor(cur);
1324                 bvcur.setSelection(true);
1325                 if (cur.top() == old) {
1326                         // We didn't move one iota, so no need to update the screen.
1327                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1328                         //cur.noUpdate();
1329                         return;
1330                 }
1331                 break;
1332         }
1333
1334         case LFUN_MOUSE_RELEASE:
1335                 switch (cmd.button()) {
1336                 case mouse_button::button1:
1337                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1338                         // If there is a new selection, update persistent selection;
1339                         // otherwise, single click does not clear persistent selection
1340                         // buffer.
1341                         if (cur.selection()) {
1342                                 // Finish selection. If double click,
1343                                 // cur is moved to the end of word by
1344                                 // selectWord but bvcur is current
1345                                 // mouse position.
1346                                 cur.bv().cursor().setSelection();
1347                                 // We might have removed an empty but drawn selection
1348                                 // (probably a margin)
1349                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1350                         } else
1351                                 cur.noUpdate();
1352                         // FIXME: We could try to handle drag and drop of selection here.
1353                         return;
1354
1355                 case mouse_button::button2:
1356                         // Middle mouse pasting is handled at mouse press time,
1357                         // see LFUN_MOUSE_PRESS.
1358                         cur.noUpdate();
1359                         return;
1360
1361                 case mouse_button::button3:
1362                         // Cursor was set at LFUN_MOUSE_PRESS time.
1363                         // FIXME: If there is a selection we could try to handle a special
1364                         // drag & drop context menu.
1365                         cur.noUpdate();
1366                         return;
1367
1368                 case mouse_button::none:
1369                 case mouse_button::button4:
1370                 case mouse_button::button5:
1371                         break;
1372                 } // switch (cmd.button())
1373
1374                 break;
1375
1376         case LFUN_SELF_INSERT: {
1377                 if (cmd.argument().empty())
1378                         break;
1379
1380                 // Automatically delete the currently selected
1381                 // text and replace it with what is being
1382                 // typed in now. Depends on lyxrc settings
1383                 // "auto_region_delete", which defaults to
1384                 // true (on).
1385
1386                 if (lyxrc.auto_region_delete && cur.selection())
1387                         cutSelection(cur, false, false);
1388
1389                 cur.clearSelection();
1390
1391                 docstring::const_iterator cit = cmd.argument().begin();
1392                 docstring::const_iterator const end = cmd.argument().end();
1393                 for (; cit != end; ++cit)
1394                         bv->translateAndInsert(*cit, this, cur);
1395
1396                 cur.resetAnchor();
1397                 moveCursor(cur, false);
1398                 bv->bookmarkEditPosition();
1399                 break;
1400         }
1401
1402         case LFUN_HYPERLINK_INSERT: {
1403                 InsetCommandParams p(HYPERLINK_CODE);
1404                 docstring content;
1405                 if (cur.selection()) {
1406                         content = cur.selectionAsString(false);
1407                         cutSelection(cur, true, false);
1408                 }
1409                 p["target"] = (cmd.argument().empty()) ?
1410                         content : cmd.argument();
1411                 string const data = InsetCommand::params2string("href", p);
1412                 if (p["target"].empty()) {
1413                         bv->showDialog("href", data);
1414                 } else {
1415                         FuncRequest fr(LFUN_INSET_INSERT, data);
1416                         dispatch(cur, fr);
1417                 }
1418                 break;
1419         }
1420
1421         case LFUN_LABEL_INSERT: {
1422                 InsetCommandParams p(LABEL_CODE);
1423                 // Try to generate a valid label
1424                 p["name"] = (cmd.argument().empty()) ?
1425                         cur.getPossibleLabel() :
1426                         cmd.argument();
1427                 string const data = InsetCommand::params2string("label", p);
1428
1429                 if (cmd.argument().empty()) {
1430                         bv->showDialog("label", data);
1431                 } else {
1432                         FuncRequest fr(LFUN_INSET_INSERT, data);
1433                         dispatch(cur, fr);
1434                 }
1435                 break;
1436         }
1437
1438         case LFUN_INFO_INSERT: {
1439                 Inset * inset;
1440                 if (cmd.argument().empty() && cur.selection()) {
1441                         // if command argument is empty use current selection as parameter.
1442                         docstring ds = cur.selectionAsString(false);
1443                         cutSelection(cur, true, false);
1444                         FuncRequest cmd0(cmd, ds);
1445                         inset = createInset(cur.bv().buffer(), cmd0);
1446                 } else {
1447                         inset = createInset(cur.bv().buffer(), cmd);
1448                 }
1449                 if (!inset)
1450                         break;
1451                 insertInset(cur, inset);
1452                 cur.posForward();
1453                 break;
1454         }
1455         case LFUN_CAPTION_INSERT:
1456         case LFUN_FOOTNOTE_INSERT:
1457         case LFUN_NOTE_INSERT:
1458         case LFUN_FLEX_INSERT:
1459         case LFUN_BOX_INSERT:
1460         case LFUN_BRANCH_INSERT:
1461         case LFUN_PHANTOM_INSERT:
1462         case LFUN_ERT_INSERT:
1463         case LFUN_LISTING_INSERT:
1464         case LFUN_MARGINALNOTE_INSERT:
1465         case LFUN_OPTIONAL_INSERT:
1466         case LFUN_INDEX_INSERT:
1467                 // Open the inset, and move the current selection
1468                 // inside it.
1469                 doInsertInset(cur, this, cmd, true, true);
1470                 cur.posForward();
1471                 // Some insets are numbered, others are shown in the outline pane so
1472                 // let's update the labels and the toc backend.
1473                 bv->buffer().updateLabels();
1474                 break;
1475
1476         case LFUN_TABULAR_INSERT:
1477                 // if there were no arguments, just open the dialog
1478                 if (doInsertInset(cur, this, cmd, false, true))
1479                         cur.posForward();
1480                 else
1481                         bv->showDialog("tabularcreate");
1482
1483                 break;
1484
1485         case LFUN_FLOAT_INSERT:
1486         case LFUN_FLOAT_WIDE_INSERT:
1487         case LFUN_WRAP_INSERT: {
1488                 // will some text be moved into the inset?
1489                 bool content = cur.selection();
1490
1491                 doInsertInset(cur, this, cmd, true, true);
1492                 cur.posForward();
1493
1494                 // If some text is moved into the inset, doInsertInset 
1495                 // puts the cursor outside the inset. To insert the
1496                 // caption we put it back into the inset.
1497                 if (content)
1498                         cur.backwardPos();
1499
1500                 ParagraphList & pars = cur.text()->paragraphs();
1501
1502                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1503
1504                 // add a separate paragraph for the caption inset
1505                 pars.push_back(Paragraph());
1506                 pars.back().setInsetOwner(&pars[0].inInset());
1507                 pars.back().setPlainOrDefaultLayout(tclass);
1508                 int cap_pit = pars.size() - 1;
1509
1510                 // if an empty inset was created, we create an additional empty
1511                 // paragraph at the bottom so that the user can choose where to put
1512                 // the graphics (or table).
1513                 if (!content) {
1514                         pars.push_back(Paragraph());
1515                         pars.back().setInsetOwner(&pars[0].inInset());
1516                         pars.back().setPlainOrDefaultLayout(tclass);
1517                 }
1518
1519                 // reposition the cursor to the caption
1520                 cur.pit() = cap_pit;
1521                 cur.pos() = 0;
1522                 // FIXME: This Text/Cursor dispatch handling is a mess!
1523                 // We cannot use Cursor::dispatch here it needs access to up to
1524                 // date metrics.
1525                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1526                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1527                 bv->buffer().updateLabels();
1528                 cur.updateFlags(Update::Force);
1529                 // FIXME: When leaving the Float (or Wrap) inset we should
1530                 // delete any empty paragraph left above or below the
1531                 // caption.
1532                 break;
1533         }
1534
1535         case LFUN_NOMENCL_INSERT: {
1536                 InsetCommandParams p(NOMENCL_CODE);
1537                 if (cmd.argument().empty())
1538                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1539                 else
1540                         p["symbol"] = cmd.argument();
1541                 string const data = InsetCommand::params2string("nomenclature", p);
1542                 bv->showDialog("nomenclature", data);
1543                 break;
1544         }
1545
1546         case LFUN_INDEX_PRINT: {
1547                 InsetCommandParams p(INDEX_PRINT_CODE);
1548                 if (cmd.argument().empty())
1549                         p["type"] = from_ascii("idx");
1550                 else
1551                         p["type"] = cmd.argument();
1552                 string const data = InsetCommand::params2string("index_print", p);
1553                 FuncRequest fr(LFUN_INSET_INSERT, data);
1554                 dispatch(cur, fr);
1555                 break;
1556         }
1557
1558         case LFUN_NOMENCL_PRINT:
1559         case LFUN_TOC_INSERT:
1560         case LFUN_LINE_INSERT:
1561         case LFUN_NEWPAGE_INSERT:
1562                 // do nothing fancy
1563                 doInsertInset(cur, this, cmd, false, false);
1564                 cur.posForward();
1565                 break;
1566
1567         case LFUN_DEPTH_DECREMENT:
1568                 changeDepth(cur, DEC_DEPTH);
1569                 break;
1570
1571         case LFUN_DEPTH_INCREMENT:
1572                 changeDepth(cur, INC_DEPTH);
1573                 break;
1574
1575         case LFUN_MATH_DISPLAY:
1576                 mathDispatch(cur, cmd, true);
1577                 break;
1578
1579         case LFUN_REGEXP_MODE:
1580                 regexpDispatch(cur, cmd);
1581                 break;
1582
1583         case LFUN_MATH_MODE:
1584                 if (cmd.argument() == "on")
1585                         // don't pass "on" as argument
1586                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1587                 else
1588                         mathDispatch(cur, cmd, false);
1589                 break;
1590
1591         case LFUN_MATH_MACRO:
1592                 if (cmd.argument().empty())
1593                         cur.errorMessage(from_utf8(N_("Missing argument")));
1594                 else {
1595                         string s = to_utf8(cmd.argument());
1596                         string const s1 = token(s, ' ', 1);
1597                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1598                         string const s2 = token(s, ' ', 2);
1599                         MacroType type = MacroTypeNewcommand;
1600                         if (s2 == "def")
1601                                 type = MacroTypeDef;
1602                         MathMacroTemplate * inset = new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type);
1603                         inset->setBuffer(bv->buffer());
1604                         insertInset(cur, inset);
1605
1606                         // enter macro inset and select the name
1607                         cur.push(*inset);
1608                         cur.top().pos() = cur.top().lastpos();
1609                         cur.resetAnchor();
1610                         cur.setSelection(true);
1611                         cur.top().pos() = 0;
1612                 }
1613                 break;
1614
1615         // passthrough hat and underscore outside mathed:
1616         case LFUN_MATH_SUBSCRIPT:
1617                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1618                 break;
1619         case LFUN_MATH_SUPERSCRIPT:
1620                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1621                 break;
1622
1623         case LFUN_MATH_INSERT:
1624         case LFUN_MATH_MATRIX:
1625         case LFUN_MATH_DELIM:
1626         case LFUN_MATH_BIGDELIM: {
1627                 cur.recordUndo();
1628                 cap::replaceSelection(cur);
1629                 cur.insert(new InsetMathHull(hullSimple));
1630                 checkAndActivateInset(cur, true);
1631                 LASSERT(cur.inMathed(), /**/);
1632                 cur.dispatch(cmd);
1633                 break;
1634         }
1635
1636         case LFUN_FONT_EMPH: {
1637                 Font font(ignore_font, ignore_language);
1638                 font.fontInfo().setEmph(FONT_TOGGLE);
1639                 toggleAndShow(cur, this, font);
1640                 break;
1641         }
1642
1643         case LFUN_FONT_ITAL: {
1644                 Font font(ignore_font, ignore_language);
1645                 font.fontInfo().setShape(ITALIC_SHAPE);
1646                 toggleAndShow(cur, this, font);
1647                 break;
1648         }
1649
1650         case LFUN_FONT_BOLD:
1651         case LFUN_FONT_BOLDSYMBOL: {
1652                 Font font(ignore_font, ignore_language);
1653                 font.fontInfo().setSeries(BOLD_SERIES);
1654                 toggleAndShow(cur, this, font);
1655                 break;
1656         }
1657
1658         case LFUN_FONT_NOUN: {
1659                 Font font(ignore_font, ignore_language);
1660                 font.fontInfo().setNoun(FONT_TOGGLE);
1661                 toggleAndShow(cur, this, font);
1662                 break;
1663         }
1664
1665         case LFUN_FONT_TYPEWRITER: {
1666                 Font font(ignore_font, ignore_language);
1667                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1668                 toggleAndShow(cur, this, font);
1669                 break;
1670         }
1671
1672         case LFUN_FONT_SANS: {
1673                 Font font(ignore_font, ignore_language);
1674                 font.fontInfo().setFamily(SANS_FAMILY);
1675                 toggleAndShow(cur, this, font);
1676                 break;
1677         }
1678
1679         case LFUN_FONT_ROMAN: {
1680                 Font font(ignore_font, ignore_language);
1681                 font.fontInfo().setFamily(ROMAN_FAMILY);
1682                 toggleAndShow(cur, this, font);
1683                 break;
1684         }
1685
1686         case LFUN_FONT_DEFAULT: {
1687                 Font font(inherit_font, ignore_language);
1688                 toggleAndShow(cur, this, font);
1689                 break;
1690         }
1691
1692         case LFUN_FONT_UNDERLINE: {
1693                 Font font(ignore_font, ignore_language);
1694                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1695                 toggleAndShow(cur, this, font);
1696                 break;
1697         }
1698
1699         case LFUN_FONT_SIZE: {
1700                 Font font(ignore_font, ignore_language);
1701                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1702                 toggleAndShow(cur, this, font);
1703                 break;
1704         }
1705
1706         case LFUN_LANGUAGE: {
1707                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1708                 if (!lang)
1709                         break;
1710                 Font font(ignore_font, lang);
1711                 toggleAndShow(cur, this, font);
1712                 break;
1713         }
1714
1715         case LFUN_TEXTSTYLE_APPLY:
1716                 toggleAndShow(cur, this, freefont, toggleall);
1717                 cur.message(_("Character set"));
1718                 break;
1719
1720         // Set the freefont using the contents of \param data dispatched from
1721         // the frontends and apply it at the current cursor location.
1722         case LFUN_TEXTSTYLE_UPDATE: {
1723                 Font font;
1724                 bool toggle;
1725                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1726                         freefont = font;
1727                         toggleall = toggle;
1728                         toggleAndShow(cur, this, freefont, toggleall);
1729                         cur.message(_("Character set"));
1730                 } else {
1731                         lyxerr << "Argument not ok";
1732                 }
1733                 break;
1734         }
1735
1736         case LFUN_FINISHED_LEFT:
1737                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1738                 // We're leaving an inset, going left. If the inset is LTR, we're
1739                 // leaving from the front, so we should not move (remain at --- but
1740                 // not in --- the inset). If the inset is RTL, move left, without
1741                 // entering the inset itself; i.e., move to after the inset.
1742                 if (cur.paragraph().getFontSettings(
1743                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1744                         cursorVisLeft(cur, true);
1745                 break;
1746
1747         case LFUN_FINISHED_RIGHT:
1748                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1749                 // We're leaving an inset, going right. If the inset is RTL, we're
1750                 // leaving from the front, so we should not move (remain at --- but
1751                 // not in --- the inset). If the inset is LTR, move right, without
1752                 // entering the inset itself; i.e., move to after the inset.
1753                 if (!cur.paragraph().getFontSettings(
1754                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1755                         cursorVisRight(cur, true);
1756                 break;
1757
1758         case LFUN_FINISHED_BACKWARD:
1759                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1760                 break;
1761
1762         case LFUN_FINISHED_FORWARD:
1763                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1764                 ++cur.pos();
1765                 cur.setCurrentFont();
1766                 break;
1767
1768         case LFUN_LAYOUT_PARAGRAPH: {
1769                 string data;
1770                 params2string(cur.paragraph(), data);
1771                 data = "show\n" + data;
1772                 bv->showDialog("paragraph", data);
1773                 break;
1774         }
1775
1776         case LFUN_PARAGRAPH_UPDATE: {
1777                 string data;
1778                 params2string(cur.paragraph(), data);
1779
1780                 // Will the paragraph accept changes from the dialog?
1781                 bool const accept =
1782                         cur.inset().allowParagraphCustomization(cur.idx());
1783
1784                 data = "update " + convert<string>(accept) + '\n' + data;
1785                 bv->updateDialog("paragraph", data);
1786                 break;
1787         }
1788
1789         case LFUN_ACCENT_UMLAUT:
1790         case LFUN_ACCENT_CIRCUMFLEX:
1791         case LFUN_ACCENT_GRAVE:
1792         case LFUN_ACCENT_ACUTE:
1793         case LFUN_ACCENT_TILDE:
1794         case LFUN_ACCENT_CEDILLA:
1795         case LFUN_ACCENT_MACRON:
1796         case LFUN_ACCENT_DOT:
1797         case LFUN_ACCENT_UNDERDOT:
1798         case LFUN_ACCENT_UNDERBAR:
1799         case LFUN_ACCENT_CARON:
1800         case LFUN_ACCENT_BREVE:
1801         case LFUN_ACCENT_TIE:
1802         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1803         case LFUN_ACCENT_CIRCLE:
1804         case LFUN_ACCENT_OGONEK:
1805                 theLyXFunc().handleKeyFunc(cmd.action);
1806                 if (!cmd.argument().empty())
1807                         // FIXME: Are all these characters encoded in one byte in utf8?
1808                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1809                 break;
1810
1811         case LFUN_FLOAT_LIST_INSERT: {
1812                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1813                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1814                         cur.recordUndo();
1815                         if (cur.selection())
1816                                 cutSelection(cur, true, false);
1817                         breakParagraph(cur);
1818
1819                         if (cur.lastpos() != 0) {
1820                                 cursorBackward(cur);
1821                                 breakParagraph(cur);
1822                         }
1823
1824                         docstring const laystr = cur.inset().usePlainLayout() ?
1825                                 tclass.plainLayoutName() :
1826                                 tclass.defaultLayoutName();
1827                         setLayout(cur, laystr);
1828                         ParagraphParameters p;
1829                         // FIXME If this call were replaced with one to clearParagraphParams(),
1830                         // then we could get rid of this method altogether.
1831                         setParagraphs(cur, p);
1832                         // FIXME This should be simplified when InsetFloatList takes a
1833                         // Buffer in its constructor.
1834                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
1835                         ifl->setBuffer(bv->buffer());
1836                         insertInset(cur, ifl);
1837                         cur.posForward();
1838                 } else {
1839                         lyxerr << "Non-existent float type: "
1840                                << to_utf8(cmd.argument()) << endl;
1841                 }
1842                 break;
1843         }
1844
1845         case LFUN_CHANGE_ACCEPT: {
1846                 acceptOrRejectChanges(cur, ACCEPT);
1847                 break;
1848         }
1849
1850         case LFUN_CHANGE_REJECT: {
1851                 acceptOrRejectChanges(cur, REJECT);
1852                 break;
1853         }
1854
1855         case LFUN_THESAURUS_ENTRY: {
1856                 docstring arg = cmd.argument();
1857                 if (arg.empty()) {
1858                         arg = cur.selectionAsString(false);
1859                         // FIXME
1860                         if (arg.size() > 100 || arg.empty()) {
1861                                 // Get word or selection
1862                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1863                                 arg = cur.selectionAsString(false);
1864                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
1865                         }
1866                 }
1867                 bv->showDialog("thesaurus", to_utf8(arg));
1868                 break;
1869         }
1870
1871         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1872                 // Given data, an encoding of the ParagraphParameters
1873                 // generated in the Paragraph dialog, this function sets
1874                 // the current paragraph, or currently selected paragraphs,
1875                 // appropriately.
1876                 // NOTE: This function overrides all existing settings.
1877                 setParagraphs(cur, cmd.argument());
1878                 cur.message(_("Paragraph layout set"));
1879                 break;
1880         }
1881
1882         case LFUN_PARAGRAPH_PARAMS: {
1883                 // Given data, an encoding of the ParagraphParameters as we'd
1884                 // find them in a LyX file, this function modifies the current paragraph,
1885                 // or currently selected paragraphs.
1886                 // NOTE: This function only modifies, and does not override, existing
1887                 // settings.
1888                 setParagraphs(cur, cmd.argument(), true);
1889                 cur.message(_("Paragraph layout set"));
1890                 break;
1891         }
1892
1893         case LFUN_ESCAPE:
1894                 if (cur.selection()) {
1895                         cur.setSelection(false);
1896                 } else {
1897                         cur.undispatched();
1898                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1899                         // correct, but I'm not 100% sure -- dov, 071019
1900                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1901                 }
1902                 break;
1903
1904         case LFUN_OUTLINE_UP:
1905                 outline(OutlineUp, cur);
1906                 setCursor(cur, cur.pit(), 0);
1907                 cur.buffer()->updateLabels();
1908                 needsUpdate = true;
1909                 break;
1910
1911         case LFUN_OUTLINE_DOWN:
1912                 outline(OutlineDown, cur);
1913                 setCursor(cur, cur.pit(), 0);
1914                 cur.buffer()->updateLabels();
1915                 needsUpdate = true;
1916                 break;
1917
1918         case LFUN_OUTLINE_IN:
1919                 outline(OutlineIn, cur);
1920                 cur.buffer()->updateLabels();
1921                 needsUpdate = true;
1922                 break;
1923
1924         case LFUN_OUTLINE_OUT:
1925                 outline(OutlineOut, cur);
1926                 cur.buffer()->updateLabels();
1927                 needsUpdate = true;
1928                 break;
1929
1930         default:
1931                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
1932                 cur.undispatched();
1933                 break;
1934         }
1935
1936         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1937
1938         // FIXME: The cursor flag is reset two lines below
1939         // so we need to check here if some of the LFUN did touch that.
1940         // for now only Text::erase() and Text::backspace() do that.
1941         // The plan is to verify all the LFUNs and then to remove this
1942         // singleParUpdate boolean altogether.
1943         if (cur.result().update() & Update::Force) {
1944                 singleParUpdate = false;
1945                 needsUpdate = true;
1946         }
1947
1948         // FIXME: the following code should go in favor of fine grained
1949         // update flag treatment.
1950         if (singleParUpdate) {
1951                 // Inserting characters does not change par height in general. So, try
1952                 // to update _only_ this paragraph. BufferView will detect if a full
1953                 // metrics update is needed anyway.
1954                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1955                 return;
1956         }
1957
1958         if (!needsUpdate
1959             && &oldTopSlice.inset() == &cur.inset()
1960             && oldTopSlice.idx() == cur.idx()
1961             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1962             && !cur.selection())
1963                 // FIXME: it would be better if we could just do this
1964                 //
1965                 //if (cur.result().update() != Update::FitCursor)
1966                 //      cur.noUpdate();
1967                 //
1968                 // But some LFUNs do not set Update::FitCursor when needed, so we
1969                 // do it for all. This is not very harmfull as FitCursor will provoke
1970                 // a full redraw only if needed but still, a proper review of all LFUN
1971                 // should be done and this needsUpdate boolean can then be removed.
1972                 cur.updateFlags(Update::FitCursor);
1973         else
1974                 cur.updateFlags(Update::Force | Update::FitCursor);
1975 }
1976
1977
1978 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1979                         FuncStatus & flag) const
1980 {
1981         LASSERT(cur.text() == this, /**/);
1982
1983         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
1984         bool enable = true;
1985         InsetCode code = NO_CODE;
1986
1987         switch (cmd.action) {
1988
1989         case LFUN_DEPTH_DECREMENT:
1990                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1991                 break;
1992
1993         case LFUN_DEPTH_INCREMENT:
1994                 enable = changeDepthAllowed(cur, INC_DEPTH);
1995                 break;
1996
1997         case LFUN_APPENDIX:
1998                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1999                 break;
2000
2001         case LFUN_DIALOG_SHOW_NEW_INSET:
2002                 if (cmd.argument() == "bibitem")
2003                         code = BIBITEM_CODE;
2004                 else if (cmd.argument() == "bibtex")
2005                         code = BIBTEX_CODE;
2006                 else if (cmd.argument() == "box")
2007                         code = BOX_CODE;
2008                 else if (cmd.argument() == "branch")
2009                         code = BRANCH_CODE;
2010                 else if (cmd.argument() == "citation")
2011                         code = CITE_CODE;
2012                 else if (cmd.argument() == "ert")
2013                         code = ERT_CODE;
2014                 else if (cmd.argument() == "external")
2015                         code = EXTERNAL_CODE;
2016                 else if (cmd.argument() == "float")
2017                         code = FLOAT_CODE;
2018                 else if (cmd.argument() == "graphics")
2019                         code = GRAPHICS_CODE;
2020                 else if (cmd.argument() == "href")
2021                         code = HYPERLINK_CODE;
2022                 else if (cmd.argument() == "include")
2023                         code = INCLUDE_CODE;
2024                 else if (cmd.argument() == "index")
2025                         code = INDEX_CODE;
2026                 else if (cmd.argument() == "index_print")
2027                         code = INDEX_PRINT_CODE;
2028                 else if (cmd.argument() == "nomenclature")
2029                         code = NOMENCL_CODE;
2030                 else if (cmd.argument() == "label")
2031                         code = LABEL_CODE;
2032                 else if (cmd.argument() == "note")
2033                         code = NOTE_CODE;
2034                 else if (cmd.argument() == "phantom")
2035                         code = PHANTOM_CODE;
2036                 else if (cmd.argument() == "ref")
2037                         code = REF_CODE;
2038                 else if (cmd.argument() == "space")
2039                         code = SPACE_CODE;
2040                 else if (cmd.argument() == "toc")
2041                         code = TOC_CODE;
2042                 else if (cmd.argument() == "vspace")
2043                         code = VSPACE_CODE;
2044                 else if (cmd.argument() == "wrap")
2045                         code = WRAP_CODE;
2046                 else if (cmd.argument() == "listings")
2047                         code = LISTINGS_CODE;
2048                 break;
2049
2050         case LFUN_ERT_INSERT:
2051                 code = ERT_CODE;
2052                 break;
2053         case LFUN_LISTING_INSERT:
2054                 code = LISTINGS_CODE;
2055                 // not allowed in description items
2056                 enable = !inDescriptionItem(cur);
2057                 break;
2058         case LFUN_FOOTNOTE_INSERT:
2059                 code = FOOT_CODE;
2060                 break;
2061         case LFUN_TABULAR_INSERT:
2062                 code = TABULAR_CODE;
2063                 break;
2064         case LFUN_MARGINALNOTE_INSERT:
2065                 code = MARGIN_CODE;
2066                 break;
2067         case LFUN_FLOAT_INSERT:
2068         case LFUN_FLOAT_WIDE_INSERT:
2069                 code = FLOAT_CODE;
2070                 // not allowed in description items
2071                 enable = !inDescriptionItem(cur);
2072                 break;
2073         case LFUN_WRAP_INSERT:
2074                 code = WRAP_CODE;
2075                 // not allowed in description items
2076                 enable = !inDescriptionItem(cur);
2077                 break;
2078         case LFUN_FLOAT_LIST_INSERT:
2079                 code = FLOAT_LIST_CODE;
2080                 break;
2081         case LFUN_CAPTION_INSERT:
2082                 code = CAPTION_CODE;
2083                 // not allowed in description items
2084                 enable = !inDescriptionItem(cur);
2085                 break;
2086         case LFUN_NOTE_INSERT:
2087                 code = NOTE_CODE;
2088                 // in commands (sections etc.) and description items,
2089                 // only Notes are allowed
2090                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2091                           (!cur.paragraph().layout().isCommand()
2092                            && !inDescriptionItem(cur)));
2093                 break;
2094         case LFUN_FLEX_INSERT: {
2095                 code = FLEX_CODE;
2096                 string s = cmd.getArg(0);
2097                 InsetLayout il =
2098                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2099                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2100                     il.lyxtype() != InsetLayout::CUSTOM &&
2101                     il.lyxtype() != InsetLayout::ELEMENT &&
2102                     il.lyxtype ()!= InsetLayout::STANDARD)
2103                         enable = false;
2104                 break;
2105                 }
2106         case LFUN_BOX_INSERT:
2107                 code = BOX_CODE;
2108                 break;
2109         case LFUN_BRANCH_INSERT:
2110                 code = BRANCH_CODE;
2111                 if (cur.buffer()->masterBuffer()->params().branchlist().empty())
2112                         enable = false;
2113                 break;
2114         case LFUN_PHANTOM_INSERT:
2115                 code = PHANTOM_CODE;
2116                 break;
2117         case LFUN_LABEL_INSERT:
2118                 code = LABEL_CODE;
2119                 break;
2120         case LFUN_INFO_INSERT:
2121                 code = INFO_CODE;
2122                 break;
2123         case LFUN_OPTIONAL_INSERT:
2124                 code = OPTARG_CODE;
2125                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2126                         < cur.paragraph().layout().optionalargs;
2127                 break;
2128         case LFUN_INDEX_INSERT:
2129                 code = INDEX_CODE;
2130                 break;
2131         case LFUN_INDEX_PRINT:
2132                 code = INDEX_PRINT_CODE;
2133                 break;
2134         case LFUN_NOMENCL_INSERT:
2135                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2136                         enable = false;
2137                         break;
2138                 }
2139                 code = NOMENCL_CODE;
2140                 break;
2141         case LFUN_NOMENCL_PRINT:
2142                 code = NOMENCL_PRINT_CODE;
2143                 break;
2144         case LFUN_TOC_INSERT:
2145                 code = TOC_CODE;
2146                 break;
2147         case LFUN_HYPERLINK_INSERT:
2148                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2149                         enable = false;
2150                         break;
2151                 }
2152                 code = HYPERLINK_CODE;
2153                 break;
2154         case LFUN_QUOTE_INSERT:
2155                 // always allow this, since we will inset a raw quote
2156                 // if an inset is not allowed.
2157                 break;
2158         case LFUN_SPECIALCHAR_INSERT:
2159                 code = SPECIALCHAR_CODE;
2160                 break;
2161         case LFUN_SPACE_INSERT:
2162                 // slight hack: we know this is allowed in math mode
2163                 if (cur.inTexted())
2164                         code = SPACE_CODE;
2165                 break;
2166
2167         case LFUN_INSET_MODIFY:
2168                 // We need to disable this, because we may get called for a
2169                 // tabular cell via
2170                 // InsetTabular::getStatus() -> InsetText::getStatus()
2171                 // and we don't handle LFUN_INSET_MODIFY.
2172                 enable = false;
2173                 break;
2174
2175         case LFUN_FONT_EMPH:
2176                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2177                 break;
2178
2179         case LFUN_FONT_ITAL:
2180                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2181                 break;
2182
2183         case LFUN_FONT_NOUN:
2184                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2185                 break;
2186
2187         case LFUN_FONT_BOLD:
2188         case LFUN_FONT_BOLDSYMBOL:
2189                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2190                 break;
2191
2192         case LFUN_FONT_SANS:
2193                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2194                 break;
2195
2196         case LFUN_FONT_ROMAN:
2197                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2198                 break;
2199
2200         case LFUN_FONT_TYPEWRITER:
2201                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2202                 break;
2203
2204         case LFUN_CUT:
2205         case LFUN_COPY:
2206                 enable = cur.selection();
2207                 break;
2208
2209         case LFUN_PASTE: {
2210                 if (cmd.argument().empty()) {
2211                         if (theClipboard().isInternal())
2212                                 enable = cap::numberOfSelections() > 0;
2213                         else
2214                                 enable = !theClipboard().empty();
2215                         break;
2216                 }
2217
2218                 // we have an argument
2219                 string const arg = to_utf8(cmd.argument());
2220                 if (isStrUnsignedInt(arg)) {
2221                         // it's a number and therefore means the internal stack
2222                         unsigned int n = convert<unsigned int>(arg);
2223                         enable = cap::numberOfSelections() > n;
2224                         break;
2225                 }
2226
2227                 // explicit graphics type?
2228                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2229                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2230                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2231                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2232                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2233                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2234                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2235                         enable = theClipboard().hasGraphicsContents(type);
2236                         break;
2237                 }
2238
2239                 // unknown argument
2240                 enable = false;
2241                 break;
2242          }
2243
2244         case LFUN_CLIPBOARD_PASTE:
2245                 enable = !theClipboard().empty();
2246                 break;
2247
2248         case LFUN_PRIMARY_SELECTION_PASTE:
2249                 enable = cur.selection() || !theSelection().empty();
2250                 break;
2251
2252         case LFUN_SELECTION_PASTE:
2253                 enable = cap::selection();
2254                 break;
2255
2256         case LFUN_PARAGRAPH_MOVE_UP:
2257                 enable = cur.pit() > 0 && !cur.selection();
2258                 break;
2259
2260         case LFUN_PARAGRAPH_MOVE_DOWN:
2261                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2262                 break;
2263
2264         case LFUN_INSET_DISSOLVE:
2265                 if (!cmd.argument().empty()) {
2266                         InsetLayout const & il = cur.inset().getLayout(cur.buffer()->params());
2267                         InsetLayout::InsetLyXType const type = 
2268                                         translateLyXType(to_utf8(cmd.argument()));
2269                         enable = cur.inset().lyxCode() == FLEX_CODE
2270                                  && il.lyxtype() == type;
2271                 } else {
2272                         enable = ((!isMainText(cur.bv().buffer())
2273                                       && cur.inset().nargs() == 1)
2274                                   || (cur.nextInset()
2275                                       && cur.nextInset()->nargs() == 1));
2276                 }
2277                 break;
2278
2279         case LFUN_CHANGE_ACCEPT:
2280         case LFUN_CHANGE_REJECT:
2281                 // In principle, these LFUNs should only be enabled if there
2282                 // is a change at the current position/in the current selection.
2283                 // However, without proper optimizations, this will inevitably
2284                 // result in unacceptable performance - just imagine a user who
2285                 // wants to select the complete content of a long document.
2286                 if (!cur.selection()) {
2287                         Change const & change = cur.paragraph().lookupChange(cur.pos());
2288                         enable = change.changed();
2289                 } else
2290                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2291                         // for selections.
2292                         enable = true;
2293                 break;
2294
2295         case LFUN_OUTLINE_UP:
2296         case LFUN_OUTLINE_DOWN:
2297         case LFUN_OUTLINE_IN:
2298         case LFUN_OUTLINE_OUT:
2299                 // FIXME: LyX is not ready for outlining within inset.
2300                 enable = isMainText(cur.bv().buffer())
2301                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2302                 break;
2303
2304         case LFUN_NEWLINE_INSERT:
2305                 // LaTeX restrictions (labels or empty par)
2306                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2307                 break;
2308
2309         case LFUN_SET_GRAPHICS_GROUP: {
2310                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2311                 if (!ins)
2312                         enable = false;
2313                 else
2314                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2315                 break;
2316         }
2317
2318         case LFUN_NEWPAGE_INSERT:
2319                 // not allowed in description items
2320                 enable = !inDescriptionItem(cur);
2321                 break;
2322
2323         case LFUN_MATH_INSERT:
2324         case LFUN_MATH_MATRIX:
2325         case LFUN_MATH_DELIM:
2326         case LFUN_MATH_BIGDELIM:
2327                 // not allowed in ERT, for example.
2328                 enable = cur.inset().insetAllowed(MATH_CODE);
2329                 break;
2330
2331         case LFUN_DATE_INSERT: {
2332                 string const format = cmd.argument().empty()
2333                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2334                 enable = support::os::is_valid_strftime(format);
2335                 break;
2336         }
2337
2338         case LFUN_WORD_DELETE_FORWARD:
2339         case LFUN_WORD_DELETE_BACKWARD:
2340         case LFUN_LINE_DELETE:
2341         case LFUN_WORD_FORWARD:
2342         case LFUN_WORD_BACKWARD:
2343         case LFUN_WORD_RIGHT:
2344         case LFUN_WORD_LEFT:
2345         case LFUN_CHAR_FORWARD:
2346         case LFUN_CHAR_FORWARD_SELECT:
2347         case LFUN_CHAR_BACKWARD:
2348         case LFUN_CHAR_BACKWARD_SELECT:
2349         case LFUN_CHAR_LEFT:
2350         case LFUN_CHAR_LEFT_SELECT:
2351         case LFUN_CHAR_RIGHT:
2352         case LFUN_CHAR_RIGHT_SELECT:
2353         case LFUN_UP:
2354         case LFUN_UP_SELECT:
2355         case LFUN_DOWN:
2356         case LFUN_DOWN_SELECT:
2357         case LFUN_PARAGRAPH_UP_SELECT:
2358         case LFUN_PARAGRAPH_DOWN_SELECT:
2359         case LFUN_LINE_BEGIN_SELECT:
2360         case LFUN_LINE_END_SELECT:
2361         case LFUN_WORD_FORWARD_SELECT:
2362         case LFUN_WORD_BACKWARD_SELECT:
2363         case LFUN_WORD_RIGHT_SELECT:
2364         case LFUN_WORD_LEFT_SELECT:
2365         case LFUN_WORD_SELECT:
2366         case LFUN_PARAGRAPH_UP:
2367         case LFUN_PARAGRAPH_DOWN:
2368         case LFUN_LINE_BEGIN:
2369         case LFUN_LINE_END:
2370         case LFUN_CHAR_DELETE_FORWARD:
2371         case LFUN_CHAR_DELETE_BACKWARD:
2372         case LFUN_BREAK_PARAGRAPH:
2373         case LFUN_PARAGRAPH_SPACING:
2374         case LFUN_INSET_INSERT:
2375         case LFUN_WORD_UPCASE:
2376         case LFUN_WORD_LOWCASE:
2377         case LFUN_WORD_CAPITALIZE:
2378         case LFUN_CHARS_TRANSPOSE:
2379         case LFUN_SERVER_GET_XY:
2380         case LFUN_SERVER_SET_XY:
2381         case LFUN_SERVER_GET_LAYOUT:
2382         case LFUN_LAYOUT:
2383         case LFUN_SELF_INSERT:
2384         case LFUN_LINE_INSERT:
2385         case LFUN_MATH_DISPLAY:
2386         case LFUN_MATH_MODE:
2387         case LFUN_MATH_MACRO:
2388         case LFUN_MATH_SUBSCRIPT:
2389         case LFUN_MATH_SUPERSCRIPT:
2390         case LFUN_FONT_DEFAULT:
2391         case LFUN_FONT_UNDERLINE:
2392         case LFUN_FONT_SIZE:
2393         case LFUN_LANGUAGE:
2394         case LFUN_TEXTSTYLE_APPLY:
2395         case LFUN_TEXTSTYLE_UPDATE:
2396         case LFUN_LAYOUT_PARAGRAPH:
2397         case LFUN_PARAGRAPH_UPDATE:
2398         case LFUN_ACCENT_UMLAUT:
2399         case LFUN_ACCENT_CIRCUMFLEX:
2400         case LFUN_ACCENT_GRAVE:
2401         case LFUN_ACCENT_ACUTE:
2402         case LFUN_ACCENT_TILDE:
2403         case LFUN_ACCENT_CEDILLA:
2404         case LFUN_ACCENT_MACRON:
2405         case LFUN_ACCENT_DOT:
2406         case LFUN_ACCENT_UNDERDOT:
2407         case LFUN_ACCENT_UNDERBAR:
2408         case LFUN_ACCENT_CARON:
2409         case LFUN_ACCENT_BREVE:
2410         case LFUN_ACCENT_TIE:
2411         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2412         case LFUN_ACCENT_CIRCLE:
2413         case LFUN_ACCENT_OGONEK:
2414         case LFUN_THESAURUS_ENTRY:
2415         case LFUN_PARAGRAPH_PARAMS_APPLY:
2416         case LFUN_PARAGRAPH_PARAMS:
2417         case LFUN_ESCAPE:
2418         case LFUN_BUFFER_BEGIN:
2419         case LFUN_BUFFER_END:
2420         case LFUN_BUFFER_BEGIN_SELECT:
2421         case LFUN_BUFFER_END_SELECT:
2422         case LFUN_INSET_BEGIN:
2423         case LFUN_INSET_END:
2424         case LFUN_INSET_BEGIN_SELECT:
2425         case LFUN_INSET_END_SELECT:
2426         case LFUN_UNICODE_INSERT:
2427                 // these are handled in our dispatch()
2428                 enable = true;
2429                 break;
2430
2431         default:
2432                 return false;
2433         }
2434
2435         if (code != NO_CODE
2436             && (cur.empty() || !cur.inset().insetAllowed(code)))
2437                 enable = false;
2438
2439         flag.setEnabled(enable);
2440         return true;
2441 }
2442
2443
2444 void Text::pasteString(Cursor & cur, docstring const & clip,
2445                 bool asParagraphs)
2446 {
2447         cur.clearSelection();
2448         if (!clip.empty()) {
2449                 cur.recordUndo();
2450                 if (asParagraphs)
2451                         insertStringAsParagraphs(cur, clip);
2452                 else
2453                         insertStringAsLines(cur, clip);
2454         }
2455 }
2456
2457
2458 // FIXME: an item inset would make things much easier.
2459 bool Text::inDescriptionItem(Cursor & cur) const
2460 {
2461         Paragraph & par = cur.paragraph();
2462         pos_type const pos = cur.pos();
2463         pos_type const body_pos = par.beginOfBody();
2464
2465         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2466             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2467                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2468                 return false;
2469
2470         return (pos < body_pos
2471                 || (pos == body_pos
2472                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2473 }
2474
2475 } // namespace lyx