]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
ae3ee5e487429c3d77effd0e07f3701e015d9a5c
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #ifdef __GNUG__
4 #pragma implementation
5 #endif
6
7 #include "BufferView_pimpl.h"
8 #include "WorkArea.h"
9 #include "lyxscreen.h"
10 #include "lyxtext.h"
11 #include "lyxrow.h"
12 #include "paragraph.h"
13 #include "LyXView.h"
14 #include "commandtags.h"
15 #include "lyxfunc.h"
16 #include "debug.h"
17 #include "font.h"
18 #include "bufferview_funcs.h"
19 #include "TextCache.h"
20 #include "bufferlist.h"
21 #include "lyxrc.h"
22 #include "intl.h"
23 // added for Dispatch functions
24 #include "lyx_cb.h"
25 #include "lyx_main.h"
26 #include "FloatList.h"
27 #include "gettext.h"
28 #include "ParagraphParameters.h"
29 #include "undo_funcs.h"
30 #include "lyxtextclasslist.h"
31
32 #include "frontends/Dialogs.h"
33 #include "frontends/Alert.h"
34 #include "frontends/FileDialog.h"
35
36 #include "insets/insetbib.h"
37 #include "insets/insettext.h"
38 #include "insets/inseturl.h"
39 #include "insets/insetlatexaccent.h"
40 #include "insets/insettoc.h"
41 #include "insets/insetref.h"
42 #include "insets/insetparent.h"
43 #include "insets/insetindex.h"
44 #include "insets/insetnote.h"
45 #include "insets/insetinclude.h"
46 #include "insets/insetcite.h"
47 #include "insets/insetert.h"
48 #include "insets/insetexternal.h"
49 #include "insets/insetgraphics.h"
50 #include "insets/insetfoot.h"
51 #include "insets/insetmarginal.h"
52 #include "insets/insetminipage.h"
53 #include "insets/insetfloat.h"
54 #include "insets/insettabular.h"
55 #if 0
56 #include "insets/insettheorem.h"
57 #include "insets/insetlist.h"
58 #endif
59 #include "insets/insetcaption.h"
60 #include "insets/insetfloatlist.h"
61 #include "insets/insetspecialchar.h"
62
63 #include "mathed/formulabase.h"
64
65 #include "support/LAssert.h"
66 #include "support/lstrings.h"
67 #include "support/filetools.h"
68 #include "support/lyxfunctional.h"
69
70 #include <ctime>
71 #include <unistd.h>
72 #include <sys/wait.h>
73 #include <clocale>
74
75
76 extern string current_layout;
77
78 using std::vector;
79 using std::find_if;
80 using std::find;
81 using std::pair;
82 using std::endl;
83 using std::make_pair;
84 using std::min;
85 using SigC::slot;
86
87 using lyx::pos_type;
88 using lyx::textclass_type;
89
90 /* the selection possible is needed, that only motion events are 
91  * used, where the bottom press event was on the drawing area too */
92 bool selection_possible = false;
93
94 extern BufferList bufferlist;
95 extern char ascii_type;
96
97 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
98
99
100 namespace {
101
102 const unsigned int saved_positions_num = 20;
103
104 inline
105 void waitForX()
106 {
107         XSync(fl_get_display(), 0);
108 }
109
110
111 void SetXtermCursor(Window win)
112 {
113         static Cursor cursor;
114         static bool cursor_undefined = true;
115         if (cursor_undefined) {
116                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
117                 XFlush(fl_get_display());
118                 cursor_undefined = false;
119         }
120         XDefineCursor(fl_get_display(), win, cursor);
121         XFlush(fl_get_display());
122 }
123
124 } // anon namespace
125
126
127 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
128              int xpos, int ypos, int width, int height)
129         : bv_(b), owner_(o), buffer_(0),
130           current_scrollbar_value(0), cursor_timeout(400),
131           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
132           inset_slept(false)
133 {
134         // Setup the signals
135         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
136         workarea_.workAreaExpose
137                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
138         workarea_.workAreaEnter
139                 .connect(slot(this, &BufferView::Pimpl::enterView));
140         workarea_.workAreaLeave
141                 .connect(slot(this, &BufferView::Pimpl::leaveView));
142         workarea_.workAreaButtonPress
143                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
144         workarea_.workAreaButtonRelease
145                 .connect(slot(this,
146                               &BufferView::Pimpl::workAreaButtonRelease));
147         workarea_.workAreaMotionNotify
148                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
149         workarea_.workAreaDoubleClick
150                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
151         workarea_.workAreaTripleClick
152                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
153         workarea_.workAreaKeyPress
154                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
155         workarea_.selectionRequested
156                 .connect(slot(this, &BufferView::Pimpl::selectionRequested)); 
157         workarea_.selectionLost
158                 .connect(slot(this, &BufferView::Pimpl::selectionLost));
159         
160         cursor_timeout.timeout.connect(slot(this,
161                                             &BufferView::Pimpl::cursorToggle));
162         cursor_timeout.start();
163         workarea_.setFocus();
164         saved_positions.resize(saved_positions_num);
165 }
166
167
168 Painter & BufferView::Pimpl::painter() 
169 {
170         return workarea_.getPainter();
171 }
172
173
174 void BufferView::Pimpl::buffer(Buffer * b)
175 {
176         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
177                             << b << ")" << endl;
178         if (buffer_) {
179                 insetSleep();
180                 buffer_->delUser(bv_);
181
182                 // Put the old text into the TextCache, but
183                 // only if the buffer is still loaded.
184                 // Also set the owner of the test to 0
185                 //              bv_->text->owner(0);
186                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
187                 if (lyxerr.debugging())
188                         textcache.show(lyxerr, "BufferView::buffer");
189                 
190                 bv_->text = 0;
191         }
192
193         // Set current buffer
194         buffer_ = b;
195
196         if (bufferlist.getState() == BufferList::CLOSING) return;
197         
198         // Nuke old image
199         // screen is always deleted when the buffer is changed.
200         screen_.reset(0);
201
202         // If we are closing the buffer, use the first buffer as current
203         if (!buffer_) {
204                 buffer_ = bufferlist.first();
205         }
206
207         if (buffer_) {
208                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
209                 buffer_->addUser(bv_);
210                 // If we don't have a text object for this, we make one
211                 if (bv_->text == 0) {
212                         resizeCurrentBuffer();
213                 } else {
214                         updateScreen();
215                         updateScrollbar();
216                 }
217                 bv_->text->first_y = screen_->topCursorVisible(bv_->text);
218                 owner_->updateMenubar();
219                 owner_->updateToolbar();
220                 // Similarly, buffer-dependent dialogs should be updated or
221                 // hidden. This should go here because some dialogs (eg ToC)
222                 // require bv_->text.
223                 owner_->getDialogs()->updateBufferDependent(true);
224                 redraw();
225                 insetWakeup();
226         } else {
227                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
228                 owner_->updateMenubar();
229                 owner_->updateToolbar();
230                 owner_->getDialogs()->hideBufferDependent();
231                 updateScrollbar();
232                 workarea_.redraw();
233
234                 // Also remove all remaining text's from the testcache.
235                 // (there should not be any!) (if there is any it is a
236                 // bug!)
237                 if (lyxerr.debugging())
238                         textcache.show(lyxerr, "buffer delete all");
239                 textcache.clear();
240         }
241         // should update layoutchoice even if we don't have a buffer.
242         owner_->updateLayoutChoice();
243
244         owner_->updateWindowTitle();
245 }
246
247
248 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
249 {
250         workarea_.resize(xpos, ypos, width, height);
251         update(bv_->text, SELECT);
252         redraw();
253 }
254
255
256 void BufferView::Pimpl::resize()
257 {
258         if (buffer_)
259                 resizeCurrentBuffer();
260 }
261
262
263 void BufferView::Pimpl::redraw()
264 {
265         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
266         workarea_.redraw();
267 }
268
269
270 bool BufferView::Pimpl::fitCursor()
271 {
272         lyx::Assert(screen_.get());
273
274         bool ret;
275
276         if (bv_->theLockingInset()) {
277                 bv_->theLockingInset()->fitInsetCursor(bv_);
278                 ret = true;
279         } else {
280                 ret = screen_->fitCursor(bv_->text, bv_);
281         }
282
283         bv_->owner()->getDialogs()->updateParagraph();
284         if (ret)
285             updateScrollbar();
286         return ret;
287 }
288
289
290 void BufferView::Pimpl::redoCurrentBuffer()
291 {
292         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
293         if (buffer_ && bv_->text) {
294                 resize();
295                 owner_->updateLayoutChoice();
296         }
297 }
298
299
300 int BufferView::Pimpl::resizeCurrentBuffer()
301 {
302         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
303         
304         Paragraph * par = 0;
305         Paragraph * selstartpar = 0;
306         Paragraph * selendpar = 0;
307         UpdatableInset * the_locking_inset = 0;
308         
309         pos_type pos = 0;
310         pos_type selstartpos = 0;
311         pos_type selendpos = 0;
312         bool selection = false;
313         bool mark_set  = false;
314         
315         owner_->prohibitInput();
316
317         owner_->message(_("Formatting document..."));
318
319         if (bv_->text) {
320                 par = bv_->text->cursor.par();
321                 pos = bv_->text->cursor.pos();
322                 selstartpar = bv_->text->selection.start.par();
323                 selstartpos = bv_->text->selection.start.pos();
324                 selendpar = bv_->text->selection.end.par();
325                 selendpos = bv_->text->selection.end.pos();
326                 selection = bv_->text->selection.set();
327                 mark_set = bv_->text->selection.mark();
328                 the_locking_inset = bv_->theLockingInset();
329                 delete bv_->text;
330                 bv_->text = new LyXText(bv_);
331                 bv_->text->init(bv_);
332                 buffer_->resizeInsets(bv_);
333         } else {
334                 // See if we have a text in TextCache that fits
335                 // the new buffer_ with the correct width.
336                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
337                 if (bv_->text) {
338                         if (lyxerr.debugging()) {
339                                 lyxerr << "Found a LyXText that fits:\n";
340                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
341                         }
342                         // Set the owner of the newly found text
343                         //      bv_->text->owner(bv_);
344                         if (lyxerr.debugging())
345                                 textcache.show(lyxerr, "resizeCurrentBuffer");
346                 } else {
347                         bv_->text = new LyXText(bv_);
348                         bv_->text->init(bv_);
349                         //buffer_->resizeInsets(bv_);
350                 }
351         }
352
353         updateScreen();
354
355         if (par) {
356                 bv_->text->selection.set(true);
357                 // At this point just to avoid the Delete-Empty-Paragraph-
358                 // Mechanism when setting the cursor.
359                 bv_->text->selection.mark(mark_set);
360                 if (selection) {
361                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
362                         bv_->text->selection.cursor = bv_->text->cursor;
363                         bv_->text->setCursor(bv_, selendpar, selendpos);
364                         bv_->text->setSelection(bv_);
365                         bv_->text->setCursor(bv_, par, pos);
366                 } else {
367                         bv_->text->setCursor(bv_, par, pos);
368                         bv_->text->selection.cursor = bv_->text->cursor;
369                         bv_->text->selection.set(false);
370                 }
371                 // remake the inset locking
372                 bv_->theLockingInset(the_locking_inset);
373         }
374
375         bv_->text->first_y = screen_->topCursorVisible(bv_->text);
376
377         // this will scroll the screen such that the cursor becomes visible
378         updateScrollbar();
379         redraw();
380
381         setState();
382         owner_->allowInput();
383
384         /// clear the "Formatting Document" message 
385         owner_->message("");
386
387         return 0;
388 }
389
390
391 void BufferView::Pimpl::updateScreen()
392 {
393         // Regenerate the screen.
394         screen_.reset(new LyXScreen(workarea_));
395 }
396
397
398 void BufferView::Pimpl::updateScrollbar()
399 {
400         /* If the text is smaller than the working area, the scrollbar
401          * maximum must be the working area height. No scrolling will 
402          * be possible */
403         if (!bv_->text) {
404                 workarea_.setScrollbar(0, 1.0);
405                 return;
406         }
407
408         long const text_height = bv_->text->height;
409         long const work_height = workarea_.height();
410
411         if (text_height <= work_height) {
412                 workarea_.setScrollbarBounds(0.0, 0.0);
413                 current_scrollbar_value = bv_->text->first_y;
414                 workarea_.setScrollbar(current_scrollbar_value, 1.0);
415                 return;
416         }
417         
418         double const lineh = bv_->text->defaultHeight();
419         double const slider_size =
420                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
421         
422         static long old_text_height;
423         static double old_lineh;
424         static double old_slider_size;
425
426         if (text_height != old_text_height) {
427                 workarea_.setScrollbarBounds(0.0,
428                                              text_height - work_height);
429                 old_text_height = text_height;
430         }
431         if (lineh != old_lineh) {
432                 workarea_.setScrollbarIncrements(lineh);
433                 old_lineh = lineh;
434         }
435         if (current_scrollbar_value != bv_->text->first_y
436             || slider_size != old_slider_size) {
437                 current_scrollbar_value = bv_->text->first_y;
438                 workarea_.setScrollbar(current_scrollbar_value, slider_size);
439                 old_slider_size = slider_size;
440         }
441 }
442
443
444 // Callback for scrollbar slider
445 void BufferView::Pimpl::scrollCB(double value)
446 {
447         if (!buffer_) return;
448
449         current_scrollbar_value = long(value);
450
451         if (current_scrollbar_value < 0)
452                 current_scrollbar_value = 0;
453    
454         if (!screen_.get())
455                 return;
456
457         screen_->draw(bv_->text, bv_, current_scrollbar_value);
458
459         if (!lyxrc.cursor_follows_scrollbar) {
460                 waitForX();
461                 return;
462         }
463  
464         LyXText * vbt = bv_->text;
465  
466         int const height = vbt->defaultHeight();
467         int const first = static_cast<int>((bv_->text->first_y + height));
468         int const last = static_cast<int>((bv_->text->first_y + workarea_.height() - height));
469
470         if (vbt->cursor.y() < first)
471                 vbt->setCursorFromCoordinates(bv_, 0, first);
472         else if (vbt->cursor.y() > last)
473                 vbt->setCursorFromCoordinates(bv_, 0, last);
474
475         waitForX();
476 }
477
478
479 int BufferView::Pimpl::scrollUp(long time)
480 {
481         if (!buffer_) return 0;
482         if (!screen_.get()) return 0;
483    
484         double value = workarea_.getScrollbarValue();
485    
486         if (value == 0) return 0;
487
488         float add_value =  (bv_->text->defaultHeight()
489                             + float(time) * float(time) * 0.125);
490    
491         if (add_value > workarea_.height())
492                 add_value = float(workarea_.height() -
493                                   bv_->text->defaultHeight());
494    
495         value -= add_value;
496
497         if (value < 0)
498                 value = 0;
499    
500         workarea_.setScrollbarValue(value);
501    
502         scrollCB(value); 
503         return 0;
504 }
505
506
507 int BufferView::Pimpl::scrollDown(long time)
508 {
509         if (!buffer_) return 0;
510         if (!screen_.get()) return 0;
511    
512         double value = workarea_.getScrollbarValue();
513         pair<float, float> p = workarea_.getScrollbarBounds();
514         double const max = p.second;
515         
516         if (value == max) return 0;
517
518         float add_value =  (bv_->text->defaultHeight()
519                             + float(time) * float(time) * 0.125);
520    
521         if (add_value > workarea_.height())
522                 add_value = float(workarea_.height() -
523                                   bv_->text->defaultHeight());
524    
525         value += add_value;
526    
527         if (value > max)
528                 value = max;
529
530         workarea_.setScrollbarValue(value);
531         
532         scrollCB(value); 
533         return 0;
534 }
535
536
537 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
538 {
539         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
540 }
541
542
543 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
544 {
545         // Only use motion with button 1
546         if (!(state & Button1MotionMask))
547                 return;
548
549         if (!buffer_ || !screen_.get()) return;
550
551         // Check for inset locking
552         if (bv_->theLockingInset()) {
553                 LyXCursor cursor = bv_->text->cursor;
554                 LyXFont font = bv_->text->getFont(buffer_,
555                                                   cursor.par(), cursor.pos());
556                 int width = bv_->theLockingInset()->width(bv_, font);
557                 int inset_x = font.isVisibleRightToLeft()
558                         ? cursor.x() - width : cursor.x();
559                 int start_x = inset_x + bv_->theLockingInset()->scroll();
560                 bv_->theLockingInset()->
561                         insetMotionNotify(bv_,
562                                           x - start_x,
563                                           y - cursor.y() + bv_->text->first_y,
564                                           state);
565                 return;
566         }
567    
568         /* The test for not selection possible is needed, that only motion
569            events are used, where the bottom press event was on
570            the drawing area too */
571         if (!selection_possible)
572                 return;
573  
574         screen_->hideCursor();
575
576         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
577       
578         if (!bv_->text->selection.set())
579                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
580       
581         bv_->text->setSelection(bv_);
582         screen_->toggleToggle(bv_->text, bv_);
583         fitCursor();
584         showCursor();
585 }
586
587
588 // Single-click on work area
589 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
590                                             unsigned int button)
591 {
592         if (!buffer_ || !screen_.get())
593                 return;
594
595         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
596
597         // ok ok, this is a hack.
598         if (button == 4 || button == 5) {
599                 switch (button) {
600                 case 4:
601                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
602                         break;
603                 case 5:
604                         scrollDown(lyxrc.wheel_jump);
605                         break;
606                 }
607         }
608         
609         // Middle button press pastes if we have a selection
610         // We do this here as if the selection was inside an inset
611         // it could get cleared on the unlocking of the inset so
612         // we have to check this first
613         bool paste_internally = false;
614         if (button == 2 && bv_->getLyXText()->selection.set()) {
615                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
616                 paste_internally = true;
617         }
618         
619         if (bv_->theLockingInset()) {
620                 // We are in inset locking mode
621                 
622                 /* Check whether the inset was hit. If not reset mode,
623                    otherwise give the event to the inset */
624                 if (inset_hit == bv_->theLockingInset()) {
625                         bv_->theLockingInset()->
626                                 insetButtonPress(bv_,xpos, ypos,button);
627                         return;
628                 } else {
629                         bv_->unlockInset(bv_->theLockingInset());
630                 }
631         }
632         
633         if (!inset_hit)
634                 selection_possible = true;
635         screen_->hideCursor();
636
637         int const screen_first = bv_->text->first_y;
638         
639         // Clear the selection
640         screen_->toggleSelection(bv_->text, bv_);
641         bv_->text->clearSelection();
642         bv_->text->fullRebreak(bv_);
643         update();
644         updateScrollbar();
645         
646         // Single left click in math inset?
647         if (isHighlyEditableInset(inset_hit)) {
648                 // Highly editable inset, like math
649                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
650                 selection_possible = false;
651                 owner_->updateLayoutChoice();
652                 owner_->message(inset->editMessage());
653                 // IMO the inset has to be first in edit-mode and then we send the
654                 // button press. (Jug 20020222)
655                 inset->edit(bv_); //, xpos, ypos, button);
656                 inset->insetButtonPress(bv_, xpos, ypos, button);
657                 return;
658         } 
659         
660         // Right click on a footnote flag opens float menu
661         if (button == 3) { 
662                 selection_possible = false;
663                 return;
664         }
665         
666         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
667                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
668         finishUndo();
669         bv_->text->selection.cursor = bv_->text->cursor;
670         bv_->text->cursor.x_fix(bv_->text->cursor.x());
671         
672         owner_->updateLayoutChoice();
673         if (fitCursor()) {
674                 selection_possible = false;
675         }
676         
677         // Insert primary selection with middle mouse
678         // if there is a local selection in the current buffer,
679         // insert this
680         if (button == 2) {
681                 if (paste_internally)
682                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
683                 else
684                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
685                                                        "paragraph");
686                 selection_possible = false;
687                 return;
688         }
689 }
690
691
692 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
693 {
694         // select a word
695         if (!buffer_)
696                 return;
697
698         LyXText * text = bv_->getLyXText();
699
700         if (text->bv_owner && bv_->theLockingInset())
701                 return;
702
703         if (screen_.get() && button == 1) {
704                 if (text->bv_owner) {
705                         screen_->hideCursor();
706                         screen_->toggleSelection(text, bv_);
707                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
708                         screen_->toggleSelection(text, bv_, false);
709                 } else {
710                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
711                 }
712                 /* This will fit the cursor on the screen
713                  * if necessary */
714                 update(text, BufferView::SELECT|BufferView::FITCUR);
715         }
716 }
717
718
719 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
720 {
721         // select a line
722         if (!buffer_)
723                 return;
724
725         LyXText * text = bv_->getLyXText();
726
727         if (text->bv_owner && bv_->theLockingInset())
728             return;
729
730         if (screen_.get() && (button == 1)) {
731                 if (text->bv_owner) {
732                         screen_->hideCursor();
733                         screen_->toggleSelection(text, bv_);
734                 }
735                 text->cursorHome(bv_);
736                 text->selection.cursor = text->cursor;
737                 text->cursorEnd(bv_);
738                 text->setSelection(bv_);
739                 if (text->bv_owner) {
740                         screen_->toggleSelection(text, bv_, false);
741                 }
742                 /* This will fit the cursor on the screen
743                  * if necessary */
744                 update(text, BufferView::SELECT|BufferView::FITCUR);
745         }
746 }
747
748
749 void BufferView::Pimpl::selectionRequested()
750 {
751         if (!available())
752                 return;
753  
754         string const sel(bv_->getLyXText()->selectionAsString(bv_->buffer(),
755                                                               false)); 
756         if (!sel.empty()) {
757                 workarea_.putClipboard(sel);
758         }
759 }
760
761  
762 void BufferView::Pimpl::selectionLost()
763 {
764         if (active() && available()) { 
765                 hideCursor();
766                 toggleSelection();
767                 bv_->getLyXText()->clearSelection();
768                 showCursor(); 
769         }
770 }
771
772  
773 void BufferView::Pimpl::enterView()
774 {
775         if (active() && available()) {
776                 SetXtermCursor(workarea_.getWin());
777                 using_xterm_cursor = true;
778         }
779 }
780
781
782 void BufferView::Pimpl::leaveView()
783 {
784         if (using_xterm_cursor) {
785                 XUndefineCursor(fl_get_display(), workarea_.getWin());
786                 using_xterm_cursor = false;
787         }
788 }
789
790
791 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
792                                               unsigned int button)
793 {
794         if (!buffer_ || !screen_.get()) return;
795
796         // If we hit an inset, we have the inset coordinates in these
797         // and inset_hit points to the inset.  If we do not hit an
798         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
799         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
800
801         if (bv_->theLockingInset()) {
802                 // We are in inset locking mode.
803
804                 /* LyX does a kind of work-area grabbing for insets.
805                    Only a ButtonPress Event outside the inset will 
806                    force a insetUnlock. */
807                 bv_->theLockingInset()->
808                         insetButtonRelease(bv_, x, y, button);
809                 return;
810         }
811         
812         selection_possible = false;
813         
814         if (button == 2)
815                 return;
816
817         // finish selection
818         if (button == 1) {
819                 workarea_.haveSelection(bv_->getLyXText()->selection.set());
820         }
821  
822         setState();
823         owner_->showState();
824         owner_->updateMenubar();
825         owner_->updateToolbar();
826
827         // Did we hit an editable inset?
828         if (inset_hit) {
829                 selection_possible = false;
830
831                 // if we reach this point with a selection, it
832                 // must mean we are currently selecting.
833                 // But we don't want to open the inset
834                 // because that is annoying for the user. 
835                 // So just pretend we didn't hit it.
836                 // this is OK because a "kosher" ButtonRelease
837                 // will follow a ButtonPress that clears
838                 // the selection.
839                 // Note this also fixes selection drawing
840                 // problems if we end up opening an inset
841                 if (bv_->getLyXText()->selection.set())
842                         return;
843  
844                 // CHECK fix this proper in 0.13
845                 // well, maybe 13.0 !!!!!!!!!
846
847                 // Following a ref shouldn't issue
848                 // a push on the undo-stack
849                 // anylonger, now that we have
850                 // keybindings for following
851                 // references and returning from
852                 // references.  IMHO though, it
853                 // should be the inset's own business
854                 // to push or not push on the undo
855                 // stack. They don't *have* to
856                 // alter the document...
857                 // (Joacim)
858                 // ...or maybe the SetCursorParUndo()
859                 // below isn't necessary at all anylonger?
860                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
861                         setCursorParUndo(bv_);
862                 }
863
864                 owner_->message(inset_hit->editMessage());
865
866                 if (isHighlyEditableInset(inset_hit)) {
867                         // Highly editable inset, like math
868                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
869                         inset->insetButtonRelease(bv_, x, y, button);
870                 } else {
871                         inset_hit->insetButtonRelease(bv_, x, y, button);
872                         inset_hit->edit(bv_, x, y, button);
873                 }
874                 return;
875         }
876
877         // Maybe we want to edit a bibitem ale970302
878         if (bv_->text->cursor.par()->bibkey && x < 20 + 
879             bibitemMaxWidth(bv_, textclasslist[buffer_->params.textclass].defaultfont())) {
880                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
881         }
882
883         return;
884 }
885
886
887 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
888                                        LyXCursor const & cursor) const
889 {
890         Paragraph /*const*/ & par = *cursor.par();
891         pos_type const pos = cursor.pos();
892
893         lyx::Assert(par.getInset(pos));
894  
895         Inset const & inset(*par.getInset(pos));
896
897         LyXFont const & font = text.getFont(buffer_, &par, pos);
898  
899         int const width = inset.width(bv_, font);
900         int const inset_x = font.isVisibleRightToLeft()
901                 ? (cursor.x() - width) : cursor.x();
902  
903         return Box(
904                 inset_x + inset.scroll(),
905                 inset_x + width,
906                 cursor.y() - inset.ascent(bv_, font),
907                 cursor.y() + inset.descent(bv_, font));
908 }
909  
910  
911 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
912                                       LyXCursor const & cursor,
913                                       int & x, int & y) const
914 {
915         pos_type const pos(cursor.pos());
916         Paragraph /*const*/ & par(*cursor.par());
917
918         if (pos >= par.size() || !par.isInset(pos)) {
919                 return 0;
920         }
921
922         Inset /*const*/ * inset = par.getInset(pos);
923  
924         if (!isEditableInset(inset)) {
925                 return 0;
926         }
927
928         Box b(insetDimensions(text, cursor));
929
930         if (!b.contained(x, y)) {
931                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y 
932                         << " box " << b << endl;
933                 return 0;
934         }
935  
936         text.setCursor(bv_, &par, pos, true);
937  
938         x -= b.x1;
939         // The origin of an inset is on the baseline
940         y -= (text.cursor.y());
941   
942         return inset;
943 }
944
945  
946 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
947 {
948         if (!screen_.get())
949                 return 0;
950   
951         int y_tmp = y + text->first_y;
952  
953         LyXCursor cursor;
954         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
955  
956         Inset * inset(checkInset(*text, cursor, x, y_tmp));
957
958         if (inset) {
959                 y = y_tmp;
960                 return inset;
961         }
962  
963         // look at previous position
964  
965         if (cursor.pos() == 0) {
966                 return 0;
967         }
968
969         // move back one
970         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
971
972         inset = checkInset(*text, cursor, x, y_tmp);
973         if (inset) {
974                 y = y_tmp;
975         }
976         return inset;
977 }
978
979
980 void BufferView::Pimpl::workAreaExpose()
981 {
982         static int work_area_width;
983         static unsigned int work_area_height;
984
985         bool const widthChange = workarea_.workWidth() != work_area_width;
986         bool const heightChange = workarea_.height() != work_area_height;
987
988         // update from work area
989         work_area_width = workarea_.workWidth();
990         work_area_height = workarea_.height();
991         if (buffer_ != 0) {
992                 if (widthChange) {
993                         // The visible LyXView need a resize
994                         owner_->resize();
995
996                         // Remove all texts from the textcache
997                         // This is not _really_ what we want to do. What
998                         // we really want to do is to delete in textcache
999                         // that does not have a BufferView with matching
1000                         // width, but as long as we have only one BufferView
1001                         // deleting all gives the same result.
1002                         if (lyxerr.debugging())
1003                                 textcache.show(lyxerr, "Expose delete all");
1004                         textcache.clear();
1005                         buffer_->resizeInsets(bv_);
1006                 } else if (heightChange) {
1007                         // Rebuild image of current screen
1008                         updateScreen();
1009                         // fitCursor() ensures we don't jump back
1010                         // to the start of the document on vertical
1011                         // resize
1012                         fitCursor();
1013
1014                         // The main window size has changed, repaint most stuff
1015                         redraw();
1016                 } else if (screen_.get())
1017                     screen_->redraw(bv_->text, bv_);
1018         } else {
1019                 // Grey box when we don't have a buffer
1020                 workarea_.greyOut();
1021         }
1022
1023         // always make sure that the scrollbar is sane.
1024         updateScrollbar();
1025         owner_->updateLayoutChoice();
1026         return;
1027 }
1028
1029
1030 void BufferView::Pimpl::update()
1031 {
1032         if (screen_.get() &&
1033                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
1034         {
1035                 LyXText::text_status st = bv_->text->status();
1036                 screen_->update(bv_->text, bv_);
1037                 bool fitc = false;
1038                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
1039                         if (bv_->text->fullRebreak(bv_)) {
1040                                 st = LyXText::NEED_MORE_REFRESH;
1041                                 bv_->text->setCursor(bv_, bv_->text->cursor.par(),
1042                                                                          bv_->text->cursor.pos());
1043                                 fitc = true;
1044                         }
1045                         bv_->text->status(bv_, st);
1046                         screen_->update(bv_->text, bv_);
1047                 }
1048                 // do this here instead of in the screen::update because of
1049                 // the above loop!
1050                 bv_->text->status(bv_, LyXText::UNCHANGED);
1051                 if (fitc)
1052                         fitCursor();
1053         }
1054 }
1055
1056 // Values used when calling update:
1057 // -3 - update
1058 // -2 - update, move sel_cursor if selection, fitcursor
1059 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1060 //  0 - update, move sel_cursor if selection, fitcursor 
1061 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1062 //  3 - update, move sel_cursor if selection
1063 //
1064 // update -
1065 // a simple redraw of the parts that need refresh
1066 //
1067 // move sel_cursor if selection -
1068 // the text's sel_cursor is moved if there is selection is progress
1069 //
1070 // fitcursor -
1071 // fitCursor() is called and the scrollbar updated
1072 //
1073 // mark dirty -
1074 // the buffer is marked dirty.
1075 //
1076 // enum {
1077 //       UPDATE = 0,
1078 //       SELECT = 1,
1079 //       FITCUR = 2,
1080 //       CHANGE = 4 
1081 // };
1082 //
1083 // UPDATE_ONLY = UPDATE;
1084 // UPDATE_SELECT = UPDATE | SELECT;
1085 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1086 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1087 //
1088 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1089 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1090 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1091 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1092 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1093
1094 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1095 {
1096         owner_->updateLayoutChoice();
1097
1098         if (!text->selection.set() && (f & SELECT)) {
1099                 text->selection.cursor = text->cursor;
1100         }
1101
1102         text->fullRebreak(bv_);
1103
1104         if (text->inset_owner) {
1105                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1106             updateInset(text->inset_owner, false);
1107         } else {
1108             update();
1109         }
1110                 
1111         if ((f & FITCUR)) {
1112                 fitCursor();
1113         }
1114
1115         if ((f & CHANGE)) {
1116                 buffer_->markDirty();
1117         }
1118 }
1119
1120
1121 // Callback for cursor timer
1122 void BufferView::Pimpl::cursorToggle()
1123 {
1124         if (!buffer_) {
1125                 cursor_timeout.restart();
1126                 return;
1127         }
1128  
1129         if (!screen_.get()) {
1130                 cursor_timeout.restart();
1131                 return;
1132         }
1133
1134         /* FIXME */
1135         extern void reapSpellchecker(void);
1136         reapSpellchecker();
1137          
1138         if (!bv_->theLockingInset()) {
1139                 screen_->cursorToggle(bv_);
1140         } else {
1141                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1142         }
1143         
1144         cursor_timeout.restart();
1145 }
1146
1147
1148 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1149 {
1150         if (!text->cursor.row()->previous())
1151                 return;
1152         
1153         int y = text->first_y;
1154         Row * cursorrow = text->cursor.row();
1155         
1156         text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1157         finishUndo();
1158         // This is to allow jumping over large insets
1159         if ((cursorrow == text->cursor.row()))
1160                 text->cursorUp(bv_);
1161         
1162         if (text->inset_owner ||
1163             text->cursor.row()->height() < workarea_.height())
1164                 screen_->draw(bv_->text, bv_,
1165                               text->cursor.y()
1166                               - text->cursor.row()->baseline()
1167                               + text->cursor.row()->height()
1168                               - workarea_.height() + 1);
1169         updateScrollbar();
1170 }
1171
1172
1173 void BufferView::Pimpl::cursorNext(LyXText * text)
1174 {
1175         if (!text->cursor.row()->next())
1176                 return;
1177         
1178         int y = text->first_y + workarea_.height();
1179 //      if (text->inset_owner)
1180 //              y += bv_->text->first;
1181         text->getRowNearY(y);
1182     
1183         Row * cursorrow = text->cursor.row();
1184         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1185         finishUndo();
1186         // This is to allow jumping over large insets
1187         if ((cursorrow == bv_->text->cursor.row()))
1188                 text->cursorDown(bv_);
1189         
1190         if (text->inset_owner ||
1191             text->cursor.row()->height() < workarea_.height())
1192                 screen_->draw(bv_->text, bv_, text->cursor.y() -
1193                               text->cursor.row()->baseline());
1194         updateScrollbar();
1195 }
1196
1197
1198 bool BufferView::Pimpl::available() const
1199 {
1200         if (buffer_ && bv_->text)
1201                 return true;
1202         return false;
1203 }
1204
1205
1206 void BufferView::Pimpl::beforeChange(LyXText * text)
1207 {
1208         toggleSelection();
1209         text->clearSelection();
1210 }
1211
1212
1213 void BufferView::Pimpl::savePosition(unsigned int i)
1214 {
1215         if (i >= saved_positions_num)
1216                 return;
1217         saved_positions[i] = Position(buffer_->fileName(),
1218                                       bv_->text->cursor.par()->id(),
1219                                       bv_->text->cursor.pos());
1220         if (i > 0) {
1221                 ostringstream str;
1222                 str << _("Saved bookmark") << ' ' << i;
1223                 owner_->message(str.str().c_str());
1224         }
1225 }
1226
1227
1228 void BufferView::Pimpl::restorePosition(unsigned int i)
1229 {
1230         if (i >= saved_positions_num)
1231                 return;
1232
1233         string const fname = saved_positions[i].filename;
1234
1235         beforeChange(bv_->text);
1236
1237         if (fname != buffer_->fileName()) {
1238                 Buffer * b = bufferlist.exists(fname) ?
1239                         bufferlist.getBuffer(fname) :
1240                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1241                 if (b != 0) buffer(b);
1242         }
1243
1244         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1245         if (!par)
1246                 return;
1247
1248         bv_->text->setCursor(bv_, par,
1249                              min(par->size(), saved_positions[i].par_pos));
1250
1251         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1252         if (i > 0) {
1253                 ostringstream str;
1254                 str << _("Moved to bookmark") << ' ' << i;
1255                 owner_->message(str.str().c_str());
1256         }
1257 }
1258
1259
1260 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1261 {
1262         if (i >= saved_positions_num)
1263                 return false;
1264
1265         return !saved_positions[i].filename.empty();
1266 }
1267
1268
1269 void BufferView::Pimpl::setState()
1270 {
1271         if (!lyxrc.rtl_support)
1272                 return;
1273
1274         LyXText * text = bv_->getLyXText();
1275         if (text->real_current_font.isRightToLeft()) {
1276                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1277                         owner_->getIntl()->KeyMapSec();
1278         } else {
1279                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1280                         owner_->getIntl()->KeyMapPrim();
1281         }
1282 }
1283
1284
1285 void BufferView::Pimpl::insetSleep()
1286 {
1287         if (bv_->theLockingInset() && !inset_slept) {
1288                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1289                 bv_->theLockingInset()->insetUnlock(bv_);
1290                 inset_slept = true;
1291         }
1292 }
1293
1294
1295 void BufferView::Pimpl::insetWakeup()
1296 {
1297         if (bv_->theLockingInset() && inset_slept) {
1298                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1299                 inset_slept = false;
1300         }
1301 }
1302
1303
1304 void BufferView::Pimpl::insetUnlock()
1305 {
1306         if (bv_->theLockingInset()) {
1307                 if (!inset_slept)
1308                         bv_->theLockingInset()->insetUnlock(bv_);
1309                 bv_->theLockingInset(0);
1310                 finishUndo();
1311                 inset_slept = false;
1312         }
1313 }
1314
1315
1316 bool BufferView::Pimpl::focus() const
1317 {
1318         return workarea_.hasFocus();
1319 }
1320
1321
1322 void BufferView::Pimpl::focus(bool f)
1323 {
1324         if (f) workarea_.setFocus();
1325 }
1326
1327
1328 bool BufferView::Pimpl::active() const
1329 {
1330         return workarea_.active();
1331 }
1332
1333
1334 bool BufferView::Pimpl::belowMouse() const 
1335 {
1336         return workarea_.belowMouse();
1337 }
1338
1339
1340 void BufferView::Pimpl::showCursor()
1341 {
1342         if (screen_.get()) {
1343                 if (bv_->theLockingInset())
1344                         bv_->theLockingInset()->showInsetCursor(bv_);
1345                 else
1346                         screen_->showCursor(bv_->text, bv_);
1347         }
1348 }
1349
1350
1351 void BufferView::Pimpl::hideCursor()
1352 {
1353         if (screen_.get()) {
1354                 if (!bv_->theLockingInset())
1355 //                      bv_->theLockingInset()->hideInsetCursor(bv_);
1356 //              else
1357                         screen_->hideCursor();
1358         }
1359 }
1360
1361
1362 void BufferView::Pimpl::toggleSelection(bool b)
1363 {
1364         if (screen_.get()) {
1365                 if (bv_->theLockingInset())
1366                         bv_->theLockingInset()->toggleSelection(bv_, b);
1367                 screen_->toggleSelection(bv_->text, bv_, b);
1368         }
1369 }
1370
1371
1372 void BufferView::Pimpl::toggleToggle()
1373 {
1374         if (screen_.get())
1375                 screen_->toggleToggle(bv_->text, bv_);
1376 }
1377
1378
1379 void BufferView::Pimpl::center() 
1380 {
1381         beforeChange(bv_->text);
1382         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1383                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1384         } else {
1385                 screen_->draw(bv_->text, bv_, 0);
1386         }
1387         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1388         redraw();
1389 }
1390
1391
1392 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1393 {
1394         if (!buffer_)
1395                 return;
1396
1397         screen_->hideCursor();
1398         beforeChange(bv_->text);
1399         
1400         string const clip(workarea_.getClipboard());
1401         
1402         if (clip.empty())
1403                 return;
1404
1405         if (asPara) {
1406                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1407         } else {
1408                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1409         }
1410         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1411 }
1412
1413
1414 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1415 {
1416         workarea_.putClipboard(stuff);
1417 }
1418
1419
1420 /*
1421  * Dispatch functions for actions which can be valid for BufferView->text
1422  * and/or InsetText->text!!!
1423  */
1424
1425
1426 inline
1427 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1428 {
1429         LyXText * lt = bv_->getLyXText();
1430         
1431         if (selecting || lt->selection.mark()) {
1432                 lt->setSelection(bv_);
1433                 if (lt->bv_owner)
1434                         toggleToggle();
1435                 else
1436                         updateInset(lt->inset_owner, false);
1437         }
1438         if (lt->bv_owner) {
1439                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1440                 showCursor();
1441         }
1442         
1443         /* ---> Everytime the cursor is moved, show the current font state. */
1444         // should this too me moved out of this func?
1445         //owner->showState();
1446         setState();
1447 }
1448
1449
1450 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1451 {
1452         LyXCursor cursor = bv_->getLyXText()->cursor;
1453         Buffer::inset_iterator it =
1454                 find_if(Buffer::inset_iterator(
1455                         cursor.par(), cursor.pos()),
1456                         buffer_->inset_iterator_end(),
1457                         lyx::compare_memfun(&Inset::lyxCode, code));
1458         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1459 }
1460
1461
1462 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1463 {
1464         string filename = filen;
1465
1466         if (filename.empty()) {
1467                 // Launch a file browser
1468                 string initpath = lyxrc.document_path;
1469
1470                 if (available()) {
1471                         string const trypath = owner_->buffer()->filePath();
1472                         // If directory is writeable, use this as default.
1473                         if (IsDirWriteable(trypath))
1474                                 initpath = trypath;
1475                 }
1476
1477                 FileDialog fileDlg(bv_->owner(),
1478                                    _("Select LyX document to insert"),
1479                         LFUN_FILE_INSERT,
1480                         make_pair(string(_("Documents|#o#O")),
1481                                   string(lyxrc.document_path)),
1482                         make_pair(string(_("Examples|#E#e")),
1483                                   string(AddPath(system_lyxdir, "examples"))));
1484
1485                 FileDialog::Result result =
1486                         fileDlg.Select(initpath,
1487                                        _("*.lyx| LyX Documents (*.lyx)"));
1488  
1489                 if (result.first == FileDialog::Later)
1490                         return;
1491
1492                 filename = result.second;
1493
1494                 // check selected filename
1495                 if (filename.empty()) {
1496                         owner_->message(_("Canceled."));
1497                         return;
1498                 }
1499         }
1500
1501         // get absolute path of file and add ".lyx" to the filename if
1502         // necessary
1503         filename = FileSearch(string(), filename, "lyx");
1504
1505         string const disp_fn(MakeDisplayPath(filename));
1506         
1507         ostringstream s1;
1508         s1 << _("Inserting document") << ' '
1509            << disp_fn << " ...";
1510         owner_->message(s1.str().c_str());
1511         bool const res = bv_->insertLyXFile(filename);
1512         if (res) {
1513                 ostringstream str;
1514                 str << _("Document") << ' ' << disp_fn
1515                     << ' ' << _("inserted.");
1516                 owner_->message(str.str().c_str());
1517         } else {
1518                 ostringstream str;
1519                 str << _("Could not insert document") << ' '
1520                     << disp_fn;
1521                 owner_->message(str.str().c_str());
1522         }
1523 }
1524
1525
1526 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1527 {
1528         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1529                               << action <<"] arg[" << argument << "]" << endl;
1530         
1531         switch (action) {
1532                 // --- Misc -------------------------------------------
1533         case LFUN_APPENDIX:
1534         {
1535                 if (available()) {
1536                         LyXText * lt = bv_->getLyXText();
1537                         lt->toggleAppendix(bv_);
1538                         update(lt,
1539                                BufferView::SELECT
1540                                | BufferView::FITCUR
1541                                | BufferView::CHANGE);
1542                 }
1543         }
1544         break;
1545
1546         case LFUN_TOC_INSERT:
1547         {
1548                 InsetCommandParams p;
1549                 p.setCmdName("tableofcontents");
1550                 Inset * inset = new InsetTOC(p);
1551                 if (!insertInset(inset, "Standard"))
1552                         delete inset;
1553                 break;
1554         }
1555                 
1556         case LFUN_SCROLL_INSET:
1557                 // this is not handled here as this funktion is only aktive
1558                 // if we have a locking_inset and that one is (or contains)
1559                 // a tabular-inset
1560                 break;
1561
1562         case LFUN_INSET_GRAPHICS:
1563         {
1564                 Inset * new_inset = new InsetGraphics;
1565                 if (!insertInset(new_inset)) {
1566                         delete new_inset;
1567                 } else {
1568                         // this is need because you don't use a inset->Edit()
1569                         updateInset(new_inset, true);
1570                         new_inset->edit(bv_);
1571                 }
1572                 break;
1573         }
1574                 
1575         case LFUN_PASTE:
1576                 bv_->paste();
1577                 setState();
1578                 break;
1579                 
1580         case LFUN_PASTESELECTION:
1581         {
1582                 bool asPara = false;
1583                 if (argument == "paragraph")
1584                         asPara = true;
1585                 pasteClipboard(asPara);
1586         }
1587         break;
1588         
1589         case LFUN_CUT:
1590                 bv_->cut();
1591                 break;
1592                 
1593         case LFUN_COPY:
1594                 bv_->copy();
1595                 break;
1596                 
1597         case LFUN_LAYOUT_COPY:
1598                 bv_->copyEnvironment();
1599                 break;
1600                 
1601         case LFUN_LAYOUT_PASTE:
1602                 bv_->pasteEnvironment();
1603                 setState();
1604                 break;
1605                 
1606         case LFUN_GOTOERROR:
1607                 gotoInset(Inset::ERROR_CODE, false);
1608                 break;
1609                 
1610         case LFUN_GOTONOTE:
1611                 gotoInset(Inset::IGNORE_CODE, false);
1612                 break;
1613
1614         case LFUN_REFERENCE_GOTO:
1615         {
1616                 vector<Inset::Code> tmp;
1617                 tmp.push_back(Inset::LABEL_CODE);
1618                 tmp.push_back(Inset::REF_CODE);
1619                 gotoInset(tmp, true);
1620                 break;
1621         }
1622
1623         case LFUN_HYPHENATION:
1624                 specialChar(InsetSpecialChar::HYPHENATION);
1625                 break;
1626                 
1627         case LFUN_LIGATURE_BREAK:
1628                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1629                 break;
1630                 
1631         case LFUN_LDOTS:
1632                 specialChar(InsetSpecialChar::LDOTS);
1633                 break;
1634                 
1635         case LFUN_END_OF_SENTENCE:
1636                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1637                 break;
1638
1639         case LFUN_MENU_SEPARATOR:
1640                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1641                 break;
1642                 
1643         case LFUN_HFILL:
1644                 hfill();
1645                 break;
1646                 
1647         case LFUN_DEPTH_MIN:
1648                 changeDepth(bv_, bv_->getLyXText(), -1);
1649                 break;
1650                 
1651         case LFUN_DEPTH_PLUS:
1652                 changeDepth(bv_, bv_->getLyXText(), 1);
1653                 break;
1654                 
1655         case LFUN_FREE:
1656                 owner_->getDialogs()->setUserFreeFont();
1657                 break;
1658
1659         case LFUN_FILE_INSERT:
1660                 MenuInsertLyXFile(argument);
1661                 break;
1662         
1663         case LFUN_FILE_INSERT_ASCII_PARA:
1664                 InsertAsciiFile(bv_, argument, true);
1665                 break;
1666
1667         case LFUN_FILE_INSERT_ASCII:
1668                 InsertAsciiFile(bv_, argument, false);
1669                 break;
1670                 
1671         case LFUN_LAYOUT:
1672         {
1673                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1674                                     << argument << endl;
1675                 
1676                 // Derive layout number from given argument (string)
1677                 // and current buffer's textclass (number). */    
1678                 textclass_type tclass = buffer_->params.textclass;
1679                 bool hasLayout =
1680                         textclasslist[tclass].hasLayout(argument);
1681                 string layout = argument;
1682
1683                 // If the entry is obsolete, use the new one instead.
1684                 if (hasLayout) {
1685                         string const & obs = textclasslist[tclass][layout]
1686                                 .obsoleted_by();
1687                         if (!obs.empty()) 
1688                                 layout = obs;
1689                 }
1690
1691                 if (!hasLayout) {
1692                         owner_->getLyXFunc()->setErrorMessage(
1693                                 string(N_("Layout ")) + argument +
1694                                 N_(" not known"));
1695                         break;
1696                 }
1697
1698                 if (current_layout != layout) {
1699                         LyXText * lt = bv_->getLyXText();
1700                         hideCursor();
1701                         current_layout = layout;
1702                         update(lt,
1703                                BufferView::SELECT
1704                                | BufferView::FITCUR);
1705                         lt->setLayout(bv_, layout);
1706                         owner_->setLayout(layout);
1707                         update(lt,
1708                                BufferView::SELECT
1709                                | BufferView::FITCUR
1710                                | BufferView::CHANGE);
1711                         setState();
1712                 }
1713         }
1714         break;
1715
1716         case LFUN_LANGUAGE:
1717                 lang(bv_, argument);
1718                 setState();
1719                 owner_->showState();
1720                 break;
1721
1722         case LFUN_EMPH:
1723                 emph(bv_);
1724                 owner_->showState();
1725                 break;
1726
1727         case LFUN_BOLD:
1728                 bold(bv_);
1729                 owner_->showState();
1730                 break;
1731                 
1732         case LFUN_NOUN:
1733                 noun(bv_);
1734                 owner_->showState();
1735                 break;
1736                 
1737         case LFUN_CODE:
1738                 code(bv_);
1739                 owner_->showState();
1740                 break;
1741                 
1742         case LFUN_SANS:
1743                 sans(bv_);
1744                 owner_->showState();
1745                 break;
1746                 
1747         case LFUN_ROMAN:
1748                 roman(bv_);
1749                 owner_->showState();
1750                 break;
1751                 
1752         case LFUN_DEFAULT:
1753                 styleReset(bv_);
1754                 owner_->showState();
1755                 break;
1756                 
1757         case LFUN_UNDERLINE:
1758                 underline(bv_);
1759                 owner_->showState();
1760                 break;
1761                 
1762         case LFUN_FONT_SIZE:
1763                 fontSize(bv_, argument);
1764                 owner_->showState();
1765                 break;
1766                 
1767         case LFUN_FONT_STATE:
1768                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1769                 break;
1770                 
1771         case LFUN_UPCASE_WORD:
1772         {
1773                 LyXText * lt = bv_->getLyXText();
1774                 
1775                 update(lt,
1776                        BufferView::SELECT
1777                        | BufferView::FITCUR);
1778                 lt->changeCase(bv_, LyXText::text_uppercase);
1779                 if (lt->inset_owner)
1780                         updateInset(lt->inset_owner, true);
1781                 update(lt,
1782                        BufferView::SELECT
1783                        | BufferView::FITCUR
1784                        | BufferView::CHANGE);
1785         }
1786         break;
1787                 
1788         case LFUN_LOWCASE_WORD:
1789         {
1790                 LyXText * lt = bv_->getLyXText();
1791                 
1792                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1793                 lt->changeCase(bv_, LyXText::text_lowercase);
1794                 if (lt->inset_owner)
1795                         updateInset(lt->inset_owner, true);
1796                 update(lt,
1797                        BufferView::SELECT
1798                        | BufferView::FITCUR
1799                        | BufferView::CHANGE);
1800         }
1801         break;
1802                 
1803         case LFUN_CAPITALIZE_WORD:
1804         {
1805                 LyXText * lt = bv_->getLyXText();
1806                 
1807                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1808                 lt->changeCase(bv_, LyXText::text_capitalization);
1809                 if (lt->inset_owner)
1810                         updateInset(lt->inset_owner, true);
1811                 update(lt,
1812                        BufferView::SELECT
1813                        | BufferView::FITCUR
1814                        | BufferView::CHANGE);
1815         }
1816         break;
1817
1818         case LFUN_TRANSPOSE_CHARS:
1819         {
1820                 LyXText * lt = bv_->getLyXText();
1821                 
1822                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1823                 lt->transposeChars(*bv_);
1824                 if (lt->inset_owner)
1825                         updateInset(lt->inset_owner, true);
1826                 update(lt,
1827                        BufferView::SELECT
1828                        | BufferView::FITCUR
1829                        | BufferView::CHANGE);
1830         }
1831         break;
1832                 
1833                                           
1834         case LFUN_INSERT_LABEL:
1835                 MenuInsertLabel(bv_, argument);
1836                 break;
1837
1838         case LFUN_REF_INSERT:
1839                 if (argument.empty()) {
1840                         InsetCommandParams p("ref");
1841                         owner_->getDialogs()->createRef(p.getAsString());
1842                 } else {
1843                         InsetCommandParams p;
1844                         p.setFromString(argument);
1845
1846                         InsetRef * inset = new InsetRef(p, *buffer_);
1847                         if (!insertInset(inset))
1848                                 delete inset;
1849                         else
1850                                 updateInset(inset, true);
1851                 }
1852                 break;
1853
1854         case LFUN_BOOKMARK_SAVE:
1855                 savePosition(strToUnsignedInt(argument));
1856                 break;
1857
1858         case LFUN_BOOKMARK_GOTO:
1859                 restorePosition(strToUnsignedInt(argument));
1860                 break;
1861
1862         case LFUN_REF_GOTO:
1863         {
1864                 string label(argument);
1865                 if (label.empty()) {
1866                         InsetRef * inset = 
1867                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1868                         if (inset) {
1869                                 label = inset->getContents();
1870                                 savePosition(0);
1871                         }
1872                 }
1873                 
1874                 if (!label.empty()) {
1875                         //bv_->savePosition(0);
1876                         if (!bv_->gotoLabel(label))
1877                                 Alert::alert(_("Error"), 
1878                                            _("Couldn't find this label"), 
1879                                            _("in current document."));
1880                 }
1881         }
1882         break;
1883                 
1884                 // --- Cursor Movements -----------------------------
1885         case LFUN_RIGHT:
1886         {
1887                 LyXText * lt = bv_->getLyXText();
1888                 
1889                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1890                 if (!lt->selection.mark())
1891                         beforeChange(lt);
1892                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1893                 if (is_rtl)
1894                         lt->cursorLeft(bv_, false);
1895                 if (lt->cursor.pos() < lt->cursor.par()->size()
1896                     && lt->cursor.par()->isInset(lt->cursor.pos())
1897                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1898                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1899                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1900                         if (is_rtl)
1901                                 tmpinset->edit(bv_, false);
1902                         else
1903                                 tmpinset->edit(bv_);
1904                         break;
1905                 }
1906                 if (!is_rtl)
1907                         lt->cursorRight(bv_, false);
1908                 finishUndo();
1909                 moveCursorUpdate(false);
1910                 owner_->showState();
1911         }
1912         break;
1913                 
1914         case LFUN_LEFT:
1915         {
1916                 // This is soooo ugly. Isn`t it possible to make
1917                 // it simpler? (Lgb)
1918                 LyXText * lt = bv_->getLyXText();
1919                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1920                 if (!lt->selection.mark())
1921                         beforeChange(lt);
1922                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1923                 LyXCursor const cur = lt->cursor;
1924                 if (!is_rtl)
1925                         lt->cursorLeft(bv_, false);
1926                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1927                     lt->cursor.pos() < lt->cursor.par()->size() &&
1928                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
1929                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1930                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1931                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1932                         if (is_rtl)
1933                                 tmpinset->edit(bv_);
1934                         else
1935                                 tmpinset->edit(bv_, false);
1936                         break;
1937                 }
1938                 if  (is_rtl)
1939                         lt->cursorRight(bv_, false);
1940
1941                 finishUndo();
1942                 moveCursorUpdate(false);
1943                 owner_->showState();
1944         }
1945         break;
1946                 
1947         case LFUN_UP:
1948         {
1949                 LyXText * lt = bv_->getLyXText();
1950                 
1951                 if (!lt->selection.mark())
1952                         beforeChange(lt);
1953                 update(lt, BufferView::UPDATE);
1954                 lt->cursorUp(bv_);
1955                 finishUndo();
1956                 moveCursorUpdate(false);
1957                 owner_->showState();
1958         }
1959         break;
1960                 
1961         case LFUN_DOWN:
1962         {
1963                 LyXText * lt = bv_->getLyXText();
1964                 
1965                 if (!lt->selection.mark())
1966                         beforeChange(lt);
1967                 update(lt, BufferView::UPDATE);
1968                 lt->cursorDown(bv_);
1969                 finishUndo();
1970                 moveCursorUpdate(false);
1971                 owner_->showState();
1972         }
1973         break;
1974
1975         case LFUN_UP_PARAGRAPH:
1976         {
1977                 LyXText * lt = bv_->getLyXText();
1978                 
1979                 if (!lt->selection.mark())
1980                         beforeChange(lt);
1981                 update(lt, BufferView::UPDATE);
1982                 lt->cursorUpParagraph(bv_);
1983                 finishUndo();
1984                 moveCursorUpdate(false);
1985                 owner_->showState();
1986         }
1987         break;
1988                 
1989         case LFUN_DOWN_PARAGRAPH:
1990         {
1991                 LyXText * lt = bv_->getLyXText();
1992                 
1993                 if (!lt->selection.mark())
1994                         beforeChange(lt);
1995                 update(lt, BufferView::UPDATE);
1996                 lt->cursorDownParagraph(bv_);
1997                 finishUndo();
1998                 moveCursorUpdate(false);
1999                 owner_->showState();
2000         }
2001         break;
2002                 
2003         case LFUN_PRIOR:
2004         {
2005                 LyXText * lt = bv_->getLyXText();
2006                 
2007                 if (!lt->selection.mark())
2008                         beforeChange(lt);
2009                 update(lt, BufferView::UPDATE);
2010                 cursorPrevious(lt);
2011                 finishUndo();
2012                 moveCursorUpdate(false);
2013                 owner_->showState();
2014         }
2015         break;
2016                 
2017         case LFUN_NEXT:
2018         {
2019                 LyXText * lt = bv_->getLyXText();
2020                 
2021                 if (!lt->selection.mark())
2022                         beforeChange(lt);
2023                 update(lt, BufferView::UPDATE);
2024                 cursorNext(lt);
2025                 finishUndo();
2026                 moveCursorUpdate(false);
2027                 owner_->showState();
2028         }
2029         break;
2030                 
2031         case LFUN_HOME:
2032         {
2033                 LyXText * lt = bv_->getLyXText();
2034                 
2035                 if (!lt->selection.mark())
2036                         beforeChange(lt);
2037                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2038                 lt->cursorHome(bv_);
2039                 finishUndo();
2040                 moveCursorUpdate(false);
2041                 owner_->showState();
2042         }
2043         break;
2044                 
2045         case LFUN_END:
2046         {
2047                 LyXText * lt = bv_->getLyXText();
2048                 
2049                 if (!lt->selection.mark())
2050                         beforeChange(lt);
2051                 update(lt,
2052                        BufferView::SELECT|BufferView::FITCUR);
2053                 lt->cursorEnd(bv_);
2054                 finishUndo();
2055                 moveCursorUpdate(false);
2056                 owner_->showState();
2057         }
2058         break;
2059                 
2060         case LFUN_SHIFT_TAB:
2061         case LFUN_TAB:
2062         {
2063                 LyXText * lt = bv_->getLyXText();
2064                 
2065                 if (!lt->selection.mark())
2066                         beforeChange(lt);
2067                 update(lt,
2068                        BufferView::SELECT|BufferView::FITCUR);
2069                 lt->cursorTab(bv_);
2070                 finishUndo();
2071                 moveCursorUpdate(false);
2072                 owner_->showState();
2073         }
2074         break;
2075                 
2076         case LFUN_WORDRIGHT:
2077         {
2078                 LyXText * lt = bv_->getLyXText();
2079                 
2080                 if (!lt->selection.mark())
2081                         beforeChange(lt);
2082                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2083                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2084                         lt->cursorLeftOneWord(bv_);
2085                 else
2086                         lt->cursorRightOneWord(bv_);
2087                 finishUndo();
2088                 moveCursorUpdate(false);
2089                 owner_->showState();
2090         }
2091         break;
2092                 
2093         case LFUN_WORDLEFT:
2094         {
2095                 LyXText * lt = bv_->getLyXText();
2096                 
2097                 if (!lt->selection.mark())
2098                         beforeChange(lt);
2099                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2100                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2101                         lt->cursorRightOneWord(bv_);
2102                 else
2103                         lt->cursorLeftOneWord(bv_);
2104                 finishUndo();
2105                 moveCursorUpdate(false);
2106                 owner_->showState();
2107         }
2108         break;
2109                 
2110         case LFUN_BEGINNINGBUF:
2111         {
2112                 LyXText * lt = bv_->getLyXText();
2113                 
2114                 if (!lt->selection.mark())
2115                         beforeChange(lt);
2116                 update(lt,
2117                        BufferView::SELECT|BufferView::FITCUR);
2118                 lt->cursorTop(bv_);
2119                 finishUndo();
2120                 moveCursorUpdate(false);
2121                 owner_->showState();
2122         }
2123         break;
2124                 
2125         case LFUN_ENDBUF:
2126         {
2127                 LyXText * lt = bv_->getLyXText();
2128                 
2129                 if (!lt->selection.mark())
2130                         beforeChange(lt);
2131                 update(lt,
2132                        BufferView::SELECT|BufferView::FITCUR);
2133                 lt->cursorBottom(bv_);
2134                 finishUndo();
2135                 moveCursorUpdate(false);
2136                 owner_->showState();
2137         }
2138         break;
2139       
2140                 /* cursor selection ---------------------------- */
2141         case LFUN_RIGHTSEL:
2142         {
2143                 LyXText * lt = bv_->getLyXText();
2144                 
2145                 update(lt,
2146                        BufferView::SELECT|BufferView::FITCUR);
2147                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2148                         lt->cursorLeft(bv_);
2149                 else
2150                         lt->cursorRight(bv_);
2151                 finishUndo();
2152                 moveCursorUpdate(true);
2153                 owner_->showState();
2154         }
2155         break;
2156                 
2157         case LFUN_LEFTSEL:
2158         {
2159                 LyXText * lt = bv_->getLyXText();
2160                 
2161                 update(lt,
2162                        BufferView::SELECT|BufferView::FITCUR);
2163                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2164                         lt->cursorRight(bv_);
2165                 else
2166                         lt->cursorLeft(bv_);
2167                 finishUndo();
2168                 moveCursorUpdate(true);
2169                 owner_->showState();
2170         }
2171         break;
2172                 
2173         case LFUN_UPSEL:
2174         {
2175                 LyXText * lt = bv_->getLyXText();
2176                 
2177                 update(lt,
2178                        BufferView::SELECT|BufferView::FITCUR);
2179                 lt->cursorUp(bv_);
2180                 finishUndo();
2181                 moveCursorUpdate(true);
2182                 owner_->showState();
2183         }
2184         break;
2185                 
2186         case LFUN_DOWNSEL:
2187         {
2188                 LyXText * lt = bv_->getLyXText();
2189                 
2190                 update(lt,
2191                        BufferView::SELECT|BufferView::FITCUR);
2192                 lt->cursorDown(bv_);
2193                 finishUndo();
2194                 moveCursorUpdate(true);
2195                 owner_->showState();
2196         }
2197         break;
2198
2199         case LFUN_UP_PARAGRAPHSEL:
2200         {
2201                 LyXText * lt = bv_->getLyXText();
2202                 
2203                 update(lt,
2204                        BufferView::SELECT|BufferView::FITCUR);
2205                 lt->cursorUpParagraph(bv_);
2206                 finishUndo();
2207                 moveCursorUpdate(true);
2208                 owner_->showState();
2209         }
2210         break;
2211                 
2212         case LFUN_DOWN_PARAGRAPHSEL:
2213         {
2214                 LyXText * lt = bv_->getLyXText();
2215                 
2216                 update(lt,
2217                        BufferView::SELECT|BufferView::FITCUR);
2218                 lt->cursorDownParagraph(bv_);
2219                 finishUndo();
2220                 moveCursorUpdate(true);
2221                 owner_->showState();
2222         }
2223         break;
2224                 
2225         case LFUN_PRIORSEL:
2226         {
2227                 LyXText * lt = bv_->getLyXText();
2228                 
2229                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2230                 cursorPrevious(lt);
2231                 finishUndo();
2232                 moveCursorUpdate(true);
2233                 owner_->showState();
2234         }
2235         break;
2236                 
2237         case LFUN_NEXTSEL:
2238         {
2239                 LyXText * lt = bv_->getLyXText();
2240                 
2241                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2242                 cursorNext(lt);
2243                 finishUndo();
2244                 moveCursorUpdate(true);
2245                 owner_->showState();
2246         }
2247         break;
2248                 
2249         case LFUN_HOMESEL:
2250         {
2251                 LyXText * lt = bv_->getLyXText();
2252                 
2253                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2254                 lt->cursorHome(bv_);
2255                 finishUndo();
2256                 moveCursorUpdate(true);
2257                 owner_->showState();
2258         }
2259         break;
2260                 
2261         case LFUN_ENDSEL:
2262         {
2263                 LyXText * lt = bv_->getLyXText();
2264
2265                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2266                 lt->cursorEnd(bv_);
2267                 finishUndo();
2268                 moveCursorUpdate(true);
2269                 owner_->showState();
2270         }
2271         break;
2272                 
2273         case LFUN_WORDRIGHTSEL:
2274         {
2275                 LyXText * lt = bv_->getLyXText();
2276                 
2277                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2278                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2279                         lt->cursorLeftOneWord(bv_);
2280                 else
2281                         lt->cursorRightOneWord(bv_);
2282                 finishUndo();
2283                 moveCursorUpdate(true);
2284                 owner_->showState();
2285         }
2286         break;
2287                 
2288         case LFUN_WORDLEFTSEL:
2289         {
2290                 LyXText * lt = bv_->getLyXText();
2291                 
2292                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2293                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2294                         lt->cursorRightOneWord(bv_);
2295                 else
2296                         lt->cursorLeftOneWord(bv_);
2297                 finishUndo();
2298                 moveCursorUpdate(true);
2299                 owner_->showState();
2300         }
2301         break;
2302                 
2303         case LFUN_BEGINNINGBUFSEL:
2304         {
2305                 LyXText * lt = bv_->getLyXText();
2306                 
2307                 if (lt->inset_owner)
2308                         break;
2309                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2310                 lt->cursorTop(bv_);
2311                 finishUndo();
2312                 moveCursorUpdate(true);
2313                 owner_->showState();
2314         }
2315         break;
2316                 
2317         case LFUN_ENDBUFSEL:
2318         {
2319                 LyXText * lt = bv_->getLyXText();
2320                 
2321                 if (lt->inset_owner)
2322                         break;
2323                 update(lt,
2324                        BufferView::SELECT|BufferView::FITCUR);
2325                 lt->cursorBottom(bv_);
2326                 finishUndo();
2327                 moveCursorUpdate(true);
2328                 owner_->showState();
2329         }
2330         break;
2331
2332                 // --- text changing commands ------------------------
2333         case LFUN_BREAKLINE:
2334         {
2335                 LyXText * lt = bv_->getLyXText();
2336
2337                 beforeChange(lt);
2338                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2339                 update(lt,
2340                        BufferView::SELECT
2341                        | BufferView::FITCUR
2342                        | BufferView::CHANGE);
2343                 moveCursorUpdate(false);
2344         }
2345         break;
2346                 
2347         case LFUN_PROTECTEDSPACE:
2348         {
2349                 LyXText * lt = bv_->getLyXText();
2350
2351                 LyXLayout const & style = textclasslist[buffer_->params.textclass][lt->cursor.par()->layout()];
2352
2353                 if (style.free_spacing) {
2354                         lt->insertChar(bv_, ' ');
2355                         update(lt,
2356                                BufferView::SELECT
2357                                | BufferView::FITCUR
2358                                | BufferView::CHANGE);
2359                 } else {
2360                         specialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
2361                 }
2362                 moveCursorUpdate(false);
2363         }
2364         break;
2365                 
2366         case LFUN_SETMARK:
2367         {
2368                 LyXText * lt = bv_->getLyXText();
2369
2370                 if (lt->selection.mark()) {
2371                         beforeChange(lt);
2372                         update(lt,
2373                                BufferView::SELECT
2374                                | BufferView::FITCUR);
2375                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2376                 } else {
2377                         beforeChange(lt);
2378                         lt->selection.mark(true);
2379                         update(lt,
2380                                BufferView::SELECT
2381                                | BufferView::FITCUR);
2382                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2383                 }
2384                 lt->selection.cursor = lt->cursor;
2385         }
2386         break;
2387                 
2388         case LFUN_DELETE:
2389         {
2390                 LyXText * lt = bv_->getLyXText();
2391
2392                 if (!lt->selection.set()) {
2393                         lt->Delete(bv_);
2394                         lt->selection.cursor = lt->cursor;
2395                         update(lt,
2396                                BufferView::SELECT
2397                                | BufferView::FITCUR
2398                                | BufferView::CHANGE);
2399                         // It is possible to make it a lot faster still
2400                         // just comment out the line below...
2401                         showCursor();
2402                 } else {
2403                         bv_->cut(false);
2404                 }
2405                 moveCursorUpdate(false);
2406                 owner_->showState();
2407                 setState();
2408         }
2409         break;
2410
2411         case LFUN_DELETE_SKIP:
2412         {
2413                 LyXText * lt = bv_->getLyXText();
2414
2415                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2416                 
2417                 LyXCursor cursor = lt->cursor;
2418
2419                 if (!lt->selection.set()) {
2420                         if (cursor.pos() == cursor.par()->size()) {
2421                                 lt->cursorRight(bv_);
2422                                 cursor = lt->cursor;
2423                                 if (cursor.pos() == 0
2424                                     && !(cursor.par()->params().spaceTop()
2425                                          == VSpace (VSpace::NONE))) {
2426                                         lt->setParagraph
2427                                                 (bv_,
2428                                                  cursor.par()->params().lineTop(),
2429                                                  cursor.par()->params().lineBottom(),
2430                                                  cursor.par()->params().pagebreakTop(), 
2431                                                  cursor.par()->params().pagebreakBottom(),
2432                                                  VSpace(VSpace::NONE), 
2433                                                  cursor.par()->params().spaceBottom(),
2434                                                  cursor.par()->params().spacing(), 
2435                                                  cursor.par()->params().align(), 
2436                                                  cursor.par()->params().labelWidthString(), 0);
2437                                         lt->cursorLeft(bv_);
2438                                         update(lt, 
2439                                                BufferView::SELECT
2440                                                | BufferView::FITCUR
2441                                                | BufferView::CHANGE);
2442                                 } else {
2443                                         lt->cursorLeft(bv_);
2444                                         lt->Delete(bv_);
2445                                         lt->selection.cursor = lt->cursor;
2446                                         update(lt,
2447                                                BufferView::SELECT
2448                                                | BufferView::FITCUR
2449                                                | BufferView::CHANGE);
2450                                 }
2451                         } else {
2452                                 lt->Delete(bv_);
2453                                 lt->selection.cursor = lt->cursor;
2454                                 update(lt,
2455                                        BufferView::SELECT
2456                                        | BufferView::FITCUR
2457                                        | BufferView::CHANGE);
2458                         }
2459                 } else {
2460                         bv_->cut(false);
2461                 }
2462         }
2463         break;
2464
2465         /* -------> Delete word forward. */
2466         case LFUN_DELETE_WORD_FORWARD:
2467                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2468                 bv_->getLyXText()->deleteWordForward(bv_);
2469                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2470                 moveCursorUpdate(false);
2471                 owner_->showState();
2472                 break;
2473
2474                 /* -------> Delete word backward. */
2475         case LFUN_DELETE_WORD_BACKWARD:
2476         {
2477                 LyXText * lt = bv_->getLyXText();
2478                 
2479                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2480                 lt->deleteWordBackward(bv_);
2481                 update(lt,
2482                        BufferView::SELECT
2483                        | BufferView::FITCUR
2484                        | BufferView::CHANGE);
2485                 moveCursorUpdate(false);
2486                 owner_->showState();
2487         }
2488         break;
2489                 
2490                 /* -------> Kill to end of line. */
2491         case LFUN_DELETE_LINE_FORWARD:
2492         {
2493                 LyXText * lt = bv_->getLyXText();
2494                 
2495                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2496                 lt->deleteLineForward(bv_);
2497                 update(lt,
2498                        BufferView::SELECT
2499                        | BufferView::FITCUR
2500                        | BufferView::CHANGE);
2501                 moveCursorUpdate(false);
2502         }
2503         break;
2504                 
2505                 /* -------> Set mark off. */
2506         case LFUN_MARK_OFF:
2507         {
2508                 LyXText * lt = bv_->getLyXText();
2509                 
2510                 beforeChange(lt);
2511                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2512                 lt->selection.cursor = lt->cursor;
2513                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2514         }
2515         break;
2516
2517                 /* -------> Set mark on. */
2518         case LFUN_MARK_ON:
2519         {
2520                 LyXText * lt = bv_->getLyXText();
2521                 
2522                 beforeChange(lt);
2523                 lt->selection.mark(true);
2524                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2525                 lt->selection.cursor = lt->cursor;
2526                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2527         }
2528         break;
2529                 
2530         case LFUN_BACKSPACE:
2531         {
2532                 LyXText * lt = bv_->getLyXText();
2533                 
2534                 if (!lt->selection.set()) {
2535                         if (owner_->getIntl()->getTrans().backspace()) {
2536                                 lt->backspace(bv_);
2537                                 lt->selection.cursor = lt->cursor;
2538                                 update(lt,
2539                                        BufferView::SELECT
2540                                        | BufferView::FITCUR
2541                                        | BufferView::CHANGE);
2542                                 // It is possible to make it a lot faster still
2543                                 // just comment out the line below...
2544                                 showCursor();
2545                         }
2546                 } else {
2547                         bv_->cut(false);
2548                 }
2549                 owner_->showState();
2550                 setState();
2551         }
2552         break;
2553
2554         case LFUN_BACKSPACE_SKIP:
2555         {
2556                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2557                 LyXText * lt = bv_->getLyXText();
2558                 
2559                 LyXCursor cursor = lt->cursor;
2560                 
2561                 if (!lt->selection.set()) {
2562                         if (cursor.pos() == 0 
2563                             && !(cursor.par()->params().spaceTop() 
2564                                  == VSpace (VSpace::NONE))) {
2565                                 lt->setParagraph 
2566                                         (bv_,
2567                                          cursor.par()->params().lineTop(),      
2568                                          cursor.par()->params().lineBottom(),
2569                                          cursor.par()->params().pagebreakTop(), 
2570                                          cursor.par()->params().pagebreakBottom(),
2571                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2572                                          cursor.par()->params().spacing(), 
2573                                          cursor.par()->params().align(), 
2574                                          cursor.par()->params().labelWidthString(), 0);
2575                                 update(lt,
2576                                        BufferView::SELECT
2577                                        | BufferView::FITCUR
2578                                        | BufferView::CHANGE);
2579                         } else {
2580                                 lt->backspace(bv_);
2581                                 lt->selection.cursor = cursor;
2582                                 update(lt,
2583                                        BufferView::SELECT
2584                                        | BufferView::FITCUR
2585                                        | BufferView::CHANGE);
2586                         }
2587                 } else
2588                         bv_->cut(false);
2589         }
2590         break;
2591
2592         case LFUN_BREAKPARAGRAPH:
2593         {
2594                 LyXText * lt = bv_->getLyXText();
2595                 
2596                 beforeChange(lt);
2597                 lt->breakParagraph(bv_, 0);
2598                 update(lt,
2599                        BufferView::SELECT
2600                        | BufferView::FITCUR
2601                        | BufferView::CHANGE);
2602                 lt->selection.cursor = lt->cursor;
2603                 setState();
2604                 owner_->showState();
2605                 break;
2606         }
2607
2608         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2609         {
2610                 LyXText * lt = bv_->getLyXText();
2611                 
2612                 beforeChange(lt);
2613                 lt->breakParagraph(bv_, 1);
2614                 update(lt,
2615                        BufferView::SELECT
2616                        | BufferView::FITCUR
2617                        | BufferView::CHANGE);
2618                 lt->selection.cursor = lt->cursor;
2619                 setState();
2620                 owner_->showState();
2621                 break;
2622         }
2623         
2624         case LFUN_BREAKPARAGRAPH_SKIP:
2625         {
2626                 // When at the beginning of a paragraph, remove
2627                 // indentation and add a "defskip" at the top.
2628                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2629                 LyXText * lt = bv_->getLyXText();
2630                 
2631                 LyXCursor cursor = lt->cursor;
2632                 
2633                 beforeChange(lt);
2634                 if (cursor.pos() == 0) {
2635                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2636                                 lt->setParagraph
2637                                         (bv_,
2638                                          cursor.par()->params().lineTop(),
2639                                          cursor.par()->params().lineBottom(),
2640                                          cursor.par()->params().pagebreakTop(),
2641                                          cursor.par()->params().pagebreakBottom(),
2642                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2643                                          cursor.par()->params().spacing(),
2644                                          cursor.par()->params().align(),
2645                                          cursor.par()->params().labelWidthString(), 1);
2646                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2647                         } 
2648                 }
2649                 else {
2650                         lt->breakParagraph(bv_, 0);
2651                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2652                 }
2653
2654                 update(lt,
2655                        BufferView::SELECT
2656                        | BufferView::FITCUR
2657                        | BufferView::CHANGE);
2658                 lt->selection.cursor = cursor;
2659                 setState();
2660                 owner_->showState();
2661         }
2662         break;
2663
2664         case LFUN_PARAGRAPH_SPACING:
2665         {
2666                 LyXText * lt = bv_->getLyXText();
2667                 
2668                 Paragraph * par = lt->cursor.par();
2669                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2670                 float cur_value = 1.0;
2671                 if (cur_spacing == Spacing::Other) {
2672                         cur_value = par->params().spacing().getValue();
2673                 }
2674                 
2675                 istringstream istr(argument.c_str());
2676
2677                 string tmp;
2678                 istr >> tmp;
2679                 Spacing::Space new_spacing = cur_spacing;
2680                 float new_value = cur_value;
2681                 if (tmp.empty()) {
2682                         lyxerr << "Missing argument to `paragraph-spacing'"
2683                                << endl;
2684                 } else if (tmp == "single") {
2685                         new_spacing = Spacing::Single;
2686                 } else if (tmp == "onehalf") {
2687                         new_spacing = Spacing::Onehalf;
2688                 } else if (tmp == "double") {
2689                         new_spacing = Spacing::Double;
2690                 } else if (tmp == "other") {
2691                         new_spacing = Spacing::Other;
2692                         float tmpval = 0.0;
2693                         istr >> tmpval;
2694                         lyxerr << "new_value = " << tmpval << endl;
2695                         if (tmpval != 0.0)
2696                                 new_value = tmpval;
2697                 } else if (tmp == "default") {
2698                         new_spacing = Spacing::Default;
2699                 } else {
2700                         lyxerr << _("Unknown spacing argument: ")
2701                                << argument << endl;
2702                 }
2703                 if (cur_spacing != new_spacing || cur_value != new_value) {
2704                         par->params().spacing(Spacing(new_spacing, new_value));
2705                         lt->redoParagraph(bv_);
2706                         update(lt,
2707                                BufferView::SELECT
2708                                | BufferView::FITCUR
2709                                | BufferView::CHANGE);
2710                 }
2711         }
2712         break;
2713         
2714         case LFUN_INSET_TOGGLE:
2715         {
2716                 LyXText * lt = bv_->getLyXText();
2717                 hideCursor();
2718                 beforeChange(lt);
2719                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2720                 lt->toggleInset(bv_);
2721                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2722                 setState();
2723         }       
2724                 break;
2725
2726         case LFUN_QUOTE:
2727                 smartQuote();
2728                 break;
2729
2730         case LFUN_HTMLURL:
2731         case LFUN_URL:
2732         {
2733                 InsetCommandParams p;
2734                 if (action == LFUN_HTMLURL)
2735                         p.setCmdName("htmlurl");
2736                 else
2737                         p.setCmdName("url");
2738                 owner_->getDialogs()->createUrl(p.getAsString());
2739         }
2740         break;
2741         
2742         case LFUN_INSERT_URL:
2743         {
2744                 InsetCommandParams p;
2745                 p.setFromString(argument);
2746
2747                 InsetUrl * inset = new InsetUrl(p);
2748                 if (!insertInset(inset))
2749                         delete inset;
2750                 else
2751                         updateInset(inset, true);
2752         }
2753         break;
2754         
2755         case LFUN_INSET_ERT:
2756                 insertAndEditInset(new InsetERT(buffer_->params));
2757                 break;
2758         
2759         case LFUN_INSET_EXTERNAL:
2760                 insertAndEditInset(new InsetExternal);
2761                 break;
2762         
2763         case LFUN_INSET_FOOTNOTE:
2764                 insertAndEditInset(new InsetFoot(buffer_->params));
2765                 break;
2766
2767         case LFUN_INSET_MARGINAL:
2768                 insertAndEditInset(new InsetMarginal(buffer_->params));
2769                 break;
2770
2771         case LFUN_INSET_MINIPAGE:
2772                 insertAndEditInset(new InsetMinipage(buffer_->params));
2773                 break;
2774
2775         case LFUN_INSERT_NOTE:
2776                 insertAndEditInset(new InsetNote(buffer_->params));
2777                 break;
2778
2779         case LFUN_INSET_FLOAT:
2780                 // check if the float type exist
2781                 if (floatList.typeExist(argument)) {
2782                         insertAndEditInset(new InsetFloat(buffer_->params,
2783                                                           argument));
2784                 } else {
2785                         lyxerr << "Non-existent float type: "
2786                                << argument << endl;
2787                 }
2788                 break;
2789
2790         case LFUN_INSET_WIDE_FLOAT:
2791         {
2792                 // check if the float type exist
2793                 if (floatList.typeExist(argument)) {
2794                         InsetFloat * new_inset =
2795                                 new InsetFloat(buffer_->params, argument);
2796                         new_inset->wide(true);
2797                         if (insertInset(new_inset))
2798                                 new_inset->edit(bv_);
2799                         else
2800                                 delete new_inset;
2801                 } else {
2802                         lyxerr << "Non-existent float type: "
2803                                << argument << endl;
2804                 }
2805                 
2806         }
2807         break;
2808
2809 #if 0
2810         case LFUN_INSET_LIST:
2811                 insertAndEditInset(new InsetList);
2812                 break;
2813
2814         case LFUN_INSET_THEOREM:
2815                 insertAndEditInset(new InsetTheorem);
2816                 break;
2817 #endif
2818                 
2819         case LFUN_INSET_CAPTION:
2820         {
2821                 // Do we have a locking inset...
2822                 if (bv_->theLockingInset()) {
2823                         lyxerr << "Locking inset code: "
2824                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2825                         InsetCaption * new_inset =
2826                                 new InsetCaption(buffer_->params);
2827                         new_inset->setOwner(bv_->theLockingInset());
2828                         new_inset->setAutoBreakRows(true);
2829                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2830                         new_inset->setFrameColor(0, LColor::captionframe);
2831                         if (insertInset(new_inset))
2832                                 new_inset->edit(bv_);
2833                         else
2834                                 delete new_inset;
2835                 }
2836         }
2837         break;
2838         
2839         case LFUN_INSET_TABULAR:
2840         {
2841                 int r = 2;
2842                 int c = 2;
2843                 if (!argument.empty())
2844                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2845                 InsetTabular * new_inset =
2846                         new InsetTabular(*buffer_, r, c);
2847                 bool const rtl =
2848                         bv_->getLyXText()->real_current_font.isRightToLeft();
2849                 if (!open_new_inset(new_inset, rtl))
2850                         delete new_inset;
2851         }
2852         break;
2853
2854         // --- lyxserver commands ----------------------------
2855
2856         case LFUN_CHARATCURSOR:
2857         {
2858                 pos_type pos = bv_->getLyXText()->cursor.pos();
2859                 if (pos < bv_->getLyXText()->cursor.par()->size())
2860                         owner_->getLyXFunc()->setMessage(
2861                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2862                 else
2863                         owner_->getLyXFunc()->setMessage("EOF");
2864         }
2865         break;
2866         
2867         case LFUN_GETXY:
2868                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2869                                                  + ' '
2870                                                  + tostr(bv_->getLyXText()->cursor.y()));
2871                 break;
2872                 
2873         case LFUN_SETXY:
2874         {
2875                 int x = 0;
2876                 int y = 0;
2877                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2878                         lyxerr << "SETXY: Could not parse coordinates in '"
2879                                << argument << std::endl;
2880                 }
2881                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2882         }
2883         break;
2884         
2885         case LFUN_GETLAYOUT:
2886                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout()));
2887                 break;
2888                         
2889         case LFUN_GETFONT:
2890         {
2891                 LyXFont & font = bv_->getLyXText()->current_font;
2892                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2893                         owner_->getLyXFunc()->setMessage("E");
2894                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2895                         owner_->getLyXFunc()->setMessage("N");
2896                 else
2897                         owner_->getLyXFunc()->setMessage("0");
2898
2899         }
2900         break;
2901
2902         // --- accented characters ---------------------------
2903                 
2904         case LFUN_UMLAUT:
2905         case LFUN_CIRCUMFLEX:
2906         case LFUN_GRAVE:
2907         case LFUN_ACUTE:
2908         case LFUN_TILDE:
2909         case LFUN_CEDILLA:
2910         case LFUN_MACRON:
2911         case LFUN_DOT:
2912         case LFUN_UNDERDOT:
2913         case LFUN_UNDERBAR:
2914         case LFUN_CARON:
2915         case LFUN_SPECIAL_CARON:
2916         case LFUN_BREVE:
2917         case LFUN_TIE:
2918         case LFUN_HUNG_UMLAUT:
2919         case LFUN_CIRCLE:
2920         case LFUN_OGONEK:
2921                 if (argument.empty()) {
2922                         // As always...
2923                         owner_->getLyXFunc()->handleKeyFunc(action);
2924                 } else {
2925                         owner_->getLyXFunc()->handleKeyFunc(action);
2926                         owner_->getIntl()->getTrans()
2927                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
2928                         update(bv_->getLyXText(),
2929                                BufferView::SELECT
2930                                | BufferView::FITCUR
2931                                | BufferView::CHANGE);
2932                 }
2933                 break;
2934         
2935         case LFUN_MATH_MACRO:
2936                 mathDispatchMathMacro(bv_, argument);
2937                 break;
2938
2939         case LFUN_MATH_DELIM:     
2940                 mathDispatchMathDelim(bv_, argument);
2941                 break;
2942
2943         case LFUN_INSERT_MATRIX:
2944                 mathDispatchInsertMatrix(bv_, argument);
2945                 break;
2946
2947         case LFUN_INSERT_MATH:
2948                 mathDispatchInsertMath(bv_, argument);
2949                 break;
2950
2951         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2952                 mathDispatchMathImportSelection(bv_, argument);
2953                 break;
2954
2955         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2956                 mathDispatchMathDisplay(bv_, argument);
2957                 break;
2958
2959         case LFUN_MATH_MODE:             // Open or create an inlined math inset 
2960                 mathDispatchMathMode(bv_, argument);
2961                 break;
2962                 
2963         case LFUN_GREEK:                 // Insert a single greek letter
2964                 mathDispatchGreek(bv_, argument);
2965                 break;
2966                 
2967         case LFUN_CITATION_INSERT:
2968         {
2969                 InsetCommandParams p;
2970                 p.setFromString(argument);
2971
2972                 InsetCitation * inset = new InsetCitation(p);
2973                 if (!insertInset(inset))
2974                         delete inset;
2975                 else
2976                         updateInset(inset, true);
2977         }
2978         break;
2979                     
2980         case LFUN_INSERT_BIBTEX:
2981         {   
2982                 // ale970405+lasgoutt970425
2983                 // The argument can be up to two tokens separated 
2984                 // by a space. The first one is the bibstyle.
2985                 string const db       = token(argument, ' ', 0);
2986                 string const bibstyle = token(argument, ' ', 1);
2987
2988                 InsetCommandParams p("BibTeX", db, bibstyle);
2989                 InsetBibtex * inset = new InsetBibtex(p);
2990                 
2991                 if (insertInset(inset)) {
2992                         if (argument.empty())
2993                                 inset->edit(bv_);
2994                 } else
2995                         delete inset;
2996         }
2997         break;
2998                 
2999         // BibTeX data bases
3000         case LFUN_BIBDB_ADD:
3001         {
3002                 InsetBibtex * inset = 
3003                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3004                 if (inset) {
3005                         inset->addDatabase(argument);
3006                 }
3007         }
3008         break;
3009                     
3010         case LFUN_BIBDB_DEL:
3011         {
3012                 InsetBibtex * inset = 
3013                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3014                 if (inset) {
3015                         inset->delDatabase(argument);
3016                 }
3017         }
3018         break;
3019         
3020         case LFUN_BIBTEX_STYLE:
3021         {
3022                 InsetBibtex * inset = 
3023                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3024                 if (inset) {
3025                         inset->setOptions(argument);
3026                 }
3027         }
3028         break;
3029                 
3030         case LFUN_INDEX_CREATE:
3031         {
3032                 InsetCommandParams p("index");
3033                 if (argument.empty()) {
3034                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3035                         p.setContents(idxstring);
3036                 } else {
3037                         p.setContents(argument);
3038                 }
3039
3040                 owner_->getDialogs()->createIndex(p.getAsString());
3041         }
3042         break;
3043                     
3044         case LFUN_INDEX_INSERT:
3045         {
3046                 InsetCommandParams p;
3047                 p.setFromString(argument);
3048                 InsetIndex * inset = new InsetIndex(p);
3049
3050                 if (!insertInset(inset))
3051                         delete inset;
3052                 else
3053                         updateInset(inset, true);
3054         }
3055         break;
3056                     
3057         case LFUN_INDEX_INSERT_LAST:
3058         {
3059                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3060                 if (!idxstring.empty()) {
3061                         owner_->message(_("Word `")
3062                                         + idxstring + _(("' indexed.")));
3063                         InsetCommandParams p("index", idxstring);
3064                         InsetIndex * inset = new InsetIndex(p);
3065                         
3066                         if (!insertInset(inset))
3067                                 delete inset;
3068                         else
3069                                 updateInset(inset, true);
3070                 }
3071         }
3072         break;
3073
3074         case LFUN_INDEX_PRINT:
3075         {
3076                 InsetCommandParams p("printindex");
3077                 Inset * inset = new InsetPrintIndex(p);
3078                 if (!insertInset(inset, "Standard"))
3079                         delete inset;
3080         }
3081         break;
3082
3083         case LFUN_PARENTINSERT:
3084         {
3085                 lyxerr << "arg " << argument << endl;
3086                 InsetCommandParams p("lyxparent", argument);
3087                 Inset * inset = new InsetParent(p, *buffer_);
3088                 if (!insertInset(inset, "Standard"))
3089                         delete inset;
3090         }
3091                  
3092         break;
3093
3094         case LFUN_CHILD_INSERT:
3095         {
3096                 InsetInclude::Params p;
3097                 p.cparams.setFromString(argument);
3098                 p.masterFilename_ = buffer_->fileName();
3099
3100                 InsetInclude * inset = new InsetInclude(p);
3101                 if (!insertInset(inset))
3102                         delete inset;
3103                 else {
3104                         updateInset(inset, true);
3105                         bv_->owner()->getDialogs()->showInclude(inset);
3106                 }
3107         }
3108         break; 
3109
3110         case LFUN_FLOAT_LIST:
3111         {
3112                 // We should check the argument for validity. (Lgb)
3113                 Inset * inset = new InsetFloatList(argument);
3114                 if (!insertInset(inset, "Standard"))
3115                         delete inset;
3116         }
3117         break;
3118         
3119         case LFUN_THESAURUS_ENTRY:
3120         {
3121                 string arg = argument;
3122
3123                 if (arg.empty()) {
3124                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3125                                                                    false);
3126  
3127                         // FIXME
3128                         if (arg.size() > 100 || arg.empty()) {
3129                                 // Get word or selection
3130                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3131                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3132                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3133                         }
3134                 }
3135
3136                 bv_->owner()->getDialogs()->showThesaurus(arg);
3137         }
3138                 break;
3139  
3140         case LFUN_SELFINSERT:
3141         {
3142                 if (argument.empty()) break;
3143                 
3144                 /* Automatically delete the currently selected
3145                  * text and replace it with what is being
3146                  * typed in now. Depends on lyxrc settings
3147                  * "auto_region_delete", which defaults to
3148                  * true (on). */
3149
3150                 LyXText * lt = bv_->getLyXText();
3151                 
3152                 if (lyxrc.auto_region_delete) {
3153                         if (lt->selection.set()) {
3154                                 lt->cutSelection(bv_, false, false);
3155                                 bv_->update(lt,
3156                                             BufferView::SELECT
3157                                             | BufferView::FITCUR
3158                                             | BufferView::CHANGE);
3159                         }
3160                 }
3161                 
3162                 beforeChange(lt);
3163                 LyXFont const old_font(lt->real_current_font);
3164                 
3165                 string::const_iterator cit = argument.begin();
3166                 string::const_iterator end = argument.end();
3167                 for (; cit != end; ++cit) {
3168                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3169                 }
3170                 
3171                 bv_->update(lt,
3172                             BufferView::SELECT
3173                             | BufferView::FITCUR
3174                             | BufferView::CHANGE);
3175                 
3176                 lt->selection.cursor = lt->cursor;
3177                 moveCursorUpdate(false);
3178                 
3179                 // real_current_font.number can change so we need to
3180                 // update the minibuffer
3181                 if (old_font != lt->real_current_font)
3182                         owner_->showState();
3183                 //return string();
3184         }
3185         break;
3186
3187         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3188         {
3189                 time_t now_time_t = time(NULL);
3190                 struct tm * now_tm = localtime(&now_time_t);
3191                 setlocale(LC_TIME, "");
3192                 string arg;
3193                 if (!argument.empty())
3194                         arg = argument;
3195                 else 
3196                         arg = lyxrc.date_insert_format;
3197                 char datetmp[32];
3198                 int const datetmp_len =
3199                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3200
3201                 LyXText * lt = bv_->getLyXText();
3202                 
3203                 for (int i = 0; i < datetmp_len; i++) {
3204                         lt->insertChar(bv_, datetmp[i]);
3205                         update(lt,
3206                                BufferView::SELECT
3207                                | BufferView::FITCUR
3208                                | BufferView::CHANGE);
3209                 }
3210
3211                 lt->selection.cursor = lt->cursor;
3212                 moveCursorUpdate(false);
3213         }
3214         break;
3215
3216         case LFUN_UNKNOWN_ACTION:
3217                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3218                 break;
3219         
3220         default:
3221                 return false;
3222         } // end of switch
3223
3224         return true;
3225 }
3226
3227
3228 void BufferView::Pimpl::newline()
3229 {
3230         if (available()) {
3231                 LyXText * lt = bv_->getLyXText();
3232                 hideCursor();
3233                 update(lt,
3234                        BufferView::SELECT
3235                        | BufferView::FITCUR);
3236                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3237                 update(lt,
3238                        BufferView::SELECT
3239                        | BufferView::FITCUR
3240                        | BufferView::CHANGE);
3241         }
3242 }
3243
3244
3245 void BufferView::Pimpl::hfill()
3246 {
3247         if (available()) {
3248                 LyXText * lt = bv_->getLyXText();
3249                 hideCursor();
3250                 update(lt,
3251                        BufferView::SELECT
3252                        | BufferView::FITCUR);
3253                 lt->insertChar(bv_, Paragraph::META_HFILL);
3254                 update(lt,
3255                        BufferView::SELECT
3256                        | BufferView::FITCUR
3257                        | BufferView::CHANGE);
3258         }
3259 }
3260
3261
3262 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3263 {
3264         if (available()) {
3265                 LyXText * lt = bv_->getLyXText();
3266                 
3267                 hideCursor();
3268                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3269                 InsetSpecialChar * new_inset = 
3270                         new InsetSpecialChar(kind);
3271                 if (!insertInset(new_inset))
3272                         delete new_inset;
3273                 else
3274                         updateInset(new_inset, true);
3275         }
3276 }
3277
3278
3279 void BufferView::Pimpl::smartQuote()
3280 {
3281         LyXText const * lt = bv_->getLyXText();
3282         Paragraph const * par = lt->cursor.par();
3283         pos_type pos = lt->cursor.pos();
3284         char c;
3285
3286         if (!pos
3287             || (par->isInset(pos - 1)
3288                 && par->getInset(pos - 1)->isSpace()))
3289                 c = ' ';
3290         else
3291                 c = par->getChar(pos - 1);
3292                 
3293
3294         hideCursor();
3295
3296         LyXLayout const & style =
3297                 textclasslist[bv_->buffer()->params.textclass][par->layout()];
3298         
3299         if (style.pass_thru ||
3300                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3301                 bv_->owner()->getLyXFunc()->dispatch(LFUN_SELFINSERT, "\"");
3302 }
3303
3304
3305 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3306 {
3307         if (insertInset(inset))
3308                 inset->edit(bv_);
3309         else
3310                 delete inset;
3311 }
3312
3313  
3314 // Open and lock an updatable inset
3315 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3316 {
3317         LyXText * lt = bv_->getLyXText();
3318         
3319         beforeChange(lt);
3320         finishUndo();
3321         if (!insertInset(new_inset)) {
3322                 delete new_inset;
3323                 return false;
3324         }
3325         new_inset->edit(bv_, !behind);
3326         return true;
3327 }
3328
3329
3330 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3331 {
3332         // if we are in a locking inset we should try to insert the
3333         // inset there otherwise this is a illegal function now
3334         if (bv_->theLockingInset()) {
3335                 if (bv_->theLockingInset()->insetAllowed(inset))
3336                     return bv_->theLockingInset()->insertInset(bv_, inset);
3337                 return false;
3338         }
3339
3340         // not quite sure if we want this...
3341         setCursorParUndo(bv_);
3342         freezeUndo();
3343         
3344         beforeChange(bv_->text);
3345         if (!lout.empty()) {
3346                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3347                 bv_->text->breakParagraph(bv_);
3348                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3349
3350                 if (bv_->text->cursor.par()->size()) {
3351                         bv_->text->cursorLeft(bv_);
3352                         
3353                         bv_->text->breakParagraph(bv_);
3354                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3355                 }
3356
3357                 string lres = lout;
3358                 LyXTextClass const & tclass =
3359                         textclasslist[buffer_->params.textclass];
3360                 bool hasLayout = tclass.hasLayout(lres);
3361                 string lay = tclass.defaultLayoutName();
3362
3363                 if (hasLayout != false) {
3364                         // layout found
3365                         lay = lres;
3366                 } else {
3367                         // layout not fount using default
3368                         lay = tclass.defaultLayoutName();
3369                 }
3370
3371                 bv_->text->setLayout(bv_, lay);
3372                 
3373                 bv_->text->setParagraph(bv_, 0, 0,
3374                                    0, 0,
3375                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3376                                    Spacing(),
3377                                    LYX_ALIGN_LAYOUT, 
3378                                    string(),
3379                                    0);
3380                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3381         }
3382         
3383         bv_->text->insertInset(bv_, inset);
3384         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3385
3386         unFreezeUndo();
3387         return true;
3388 }
3389
3390
3391 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3392 {
3393         if (!inset || !available())
3394                 return;
3395
3396         // first check for locking insets
3397         if (bv_->theLockingInset()) {
3398                 if (bv_->theLockingInset() == inset) {
3399                         if (bv_->text->updateInset(bv_, inset)) {
3400                                 update();
3401                                 if (mark_dirty) {
3402                                         buffer_->markDirty();
3403                                 }
3404                                 updateScrollbar();
3405                                 return;
3406                         }
3407                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3408                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3409                                 update();
3410                                 if (mark_dirty) {
3411                                         buffer_->markDirty();
3412                                 }
3413                                 updateScrollbar();
3414                                 return;
3415                         }
3416                 }
3417         }
3418   
3419         // then check if the inset is a top_level inset (has no owner)
3420         // if yes do the update as always otherwise we have to update the
3421         // toplevel inset where this inset is inside
3422         Inset * tl_inset = inset;
3423         while(tl_inset->owner())
3424                 tl_inset = tl_inset->owner();
3425         hideCursor();
3426         if (tl_inset == inset) {
3427                 update(bv_->text, BufferView::UPDATE);
3428                 if (bv_->text->updateInset(bv_, inset)) {
3429                         if (mark_dirty) {
3430                                 update(bv_->text,
3431                                        BufferView::SELECT
3432                                        | BufferView::FITCUR
3433                                        | BufferView::CHANGE);
3434                         } else {
3435                                 update(bv_->text, SELECT);
3436                         }
3437                         return;
3438                 }
3439         } else if (static_cast<UpdatableInset *>(tl_inset)
3440                            ->updateInsetInInset(bv_, inset))
3441         {
3442                         if (bv_->text->updateInset(bv_,  tl_inset)) {
3443                                 update();
3444                                 updateScrollbar();
3445                         }
3446         }
3447 }
3448
3449
3450 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3451                                   bool same_content)
3452 {
3453         if (!available()) return;
3454         
3455         hideCursor();
3456         beforeChange(bv_->text);
3457         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3458         
3459         LyXCursor const & cursor = bv_->text->cursor;
3460  
3461         string contents;
3462         if (same_content &&
3463             cursor.par()->isInset(cursor.pos())) {
3464                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3465                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3466                     != codes.end())
3467                         contents =
3468                                 static_cast<InsetCommand const *>(inset)->getContents();
3469         }
3470         
3471  
3472         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3473                 if (bv_->text->cursor.pos() 
3474                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3475                         LyXCursor tmp = bv_->text->cursor;
3476                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3477                         bv_->text->cursor.pos(0);
3478                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3479                                 bv_->text->cursor = tmp;
3480                                 bv_->owner()->message(_("No more insets"));
3481                         }
3482                 } else {
3483                         bv_->owner()->message(_("No more insets"));
3484                 }
3485         }
3486         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3487         bv_->text->selection.cursor = bv_->text->cursor;
3488 }
3489
3490
3491 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3492 {
3493         gotoInset(vector<Inset::Code>(1, code), same_content);
3494 }