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