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