]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
Forgot this...
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
28 #include "factory.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
32 #include "gettext.h"
33 #include "intl.h"
34 #include "insetiterator.h"
35 #include "language.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
38 #include "lyx_main.h"
39 #include "lyxfind.h"
40 #include "lyxfunc.h"
41 #include "lyxlayout.h"
42 #include "lyxtext.h"
43 #include "lyxtextclass.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "texrow.h"
51 #include "toc.h"
52 #include "undo.h"
53 #include "vspace.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
61
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
65
66 #include "graphics/Previews.h"
67
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
73
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
76
77 #include <functional>
78 #include <vector>
79
80
81 namespace lyx {
82
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
91
92 using std::distance;
93 using std::endl;
94 using std::istringstream;
95 using std::make_pair;
96 using std::min;
97 using std::max;
98 using std::mem_fun_ref;
99 using std::string;
100 using std::vector;
101
102 namespace Alert = frontend::Alert;
103
104 namespace {
105
106 /// Return an inset of this class if it exists at the current cursor position
107 template <class T>
108 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
109 {
110         T * inset = 0;
111         DocIterator it = cur;
112         if (it.nextInset() &&
113             it.nextInset()->lyxCode() == code) {
114                 inset = static_cast<T*>(it.nextInset());
115         }
116         return inset;
117 }
118
119 } // anon namespace
120
121
122 BufferView::BufferView()
123         : width_(0), height_(0), buffer_(0), wh_(0),
124           cursor_(*this),
125           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
126           intl_(new Intl)
127 {
128         xsel_cache_.set = false;
129         intl_->initKeyMapper(lyxrc.use_kbmap);
130 }
131
132
133 BufferView::~BufferView()
134 {
135 }
136
137
138 Buffer * BufferView::buffer() const
139 {
140         return buffer_;
141 }
142
143
144 void BufferView::setBuffer(Buffer * b)
145 {
146         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
147                             << "[ b = " << b << "]" << endl;
148
149         if (buffer_) {
150                 // Save the actual cursor position and anchor inside the
151                 // buffer so that it can be restored in case we rechange
152                 // to this buffer later on.
153                 buffer_->saveCursor(cursor_.selectionBegin(),
154                                     cursor_.selectionEnd());
155                 // current buffer is going to be switched-off, save cursor pos
156                 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
157                         boost::tie(cursor_.pit(), cursor_.pos()) );
158         }
159
160         // If we're quitting lyx, don't bother updating stuff
161         if (quitting) {
162                 buffer_ = 0;
163                 return;
164         }
165
166         // If we are closing current buffer, switch to the first in
167         // buffer list.
168         if (!b) {
169                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
170                                     << " No Buffer!" << endl;
171                 // We are closing the buffer, use the first buffer as current
172                 buffer_ = theBufferList().first();
173         } else {
174                 // Set current buffer
175                 buffer_ = b;
176         }
177
178         // Reset old cursor
179         cursor_ = LCursor(*this);
180         anchor_ref_ = 0;
181         offset_ref_ = 0;
182
183         if (buffer_) {
184                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185                                     << "Buffer addr: " << buffer_ << endl;
186                 cursor_.push(buffer_->inset());
187                 cursor_.resetAnchor();
188                 buffer_->text().init(this);
189                 buffer_->text().setCurrentFont(cursor_);
190                 if (buffer_->getCursor().size() > 0 &&
191                     buffer_->getAnchor().size() > 0)
192                 {
193                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
194                         cursor_.resetAnchor();
195                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
196                         cursor_.setSelection();
197                 }
198         }
199
200         update();
201
202         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
203                 graphics::Previews::get().generateBufferPreviews(*buffer_);
204 }
205
206
207 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
208 {
209         // Get absolute path of file and add ".lyx"
210         // to the filename if necessary
211         string s = fileSearch(string(), filename, "lyx");
212
213         bool const found = !s.empty();
214
215         if (!found)
216                 s = filename;
217
218         // File already open?
219         if (theBufferList().exists(s)) {
220                 docstring const file = makeDisplayPath(s, 20);
221                 docstring text = bformat(_("The document %1$s is already "
222                                                      "loaded.\n\nDo you want to revert "
223                                                      "to the saved version?"), file);
224                 int const ret = Alert::prompt(_("Revert to saved document?"),
225                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
226
227                 if (ret != 0) {
228                         setBuffer(theBufferList().getBuffer(s));
229                         return true;
230                 }
231                 // FIXME: should be LFUN_REVERT
232                 if (!theBufferList().close(theBufferList().getBuffer(s), false))
233                         return false;
234                 // Fall through to new load. (Asger)
235                 buffer_ = 0;
236         }
237
238         Buffer * b = 0;
239
240         if (found) {
241                 b = theBufferList().newBuffer(s);
242                 if (!lyx::loadLyXFile(b, s)) {
243                         theBufferList().release(b);
244                         return false;
245                 }
246         } else {
247                 docstring text = bformat(_("The document %1$s does not yet "
248                                                      "exist.\n\nDo you want to create "
249                                                      "a new document?"), from_utf8(s));
250                 int const ret = Alert::prompt(_("Create new document?"),
251                          text, 0, 1, _("&Create"), _("Cancel"));
252
253                 if (ret == 0) {
254                         b = newFile(s, string(), true);
255                         if (!b)
256                                 return false;
257                 } else
258                         return false;
259         }
260
261         setBuffer(b);
262         // Send the "errors" signal in case of parsing errors
263         b->errors("Parse");
264
265         // scroll to the position when the file was last closed
266         if (lyxrc.use_lastfilepos) {
267                 pit_type pit;
268                 pos_type pos;
269                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
270                 // I am not sure how to separate the following part to a function
271                 // so I will leave this to Lars.
272                 //
273                 // check pit since the document may be externally changed.
274                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
275                         ParIterator it = b->par_iterator_begin();
276                         ParIterator const end = b->par_iterator_end();
277                         for (; it != end; ++it)
278                                 if (it.pit() == pit) {
279                                         // restored pos may be bigger than it->size
280                                         setCursor(makeDocIterator(it, min(pos, it->size())));
281                                         update(Update::FitCursor);
282                                         break;
283                                 }
284                 }
285         }
286
287         if (tolastfiles)
288                 LyX::ref().session().lastFiles().add(b->fileName());
289
290         return true;
291 }
292
293
294 void BufferView::reload()
295 {
296         string const fn = buffer_->fileName();
297         if (theBufferList().close(buffer_, false))
298                 loadLyXFile(fn);
299 }
300
301
302 void BufferView::resize()
303 {
304         if (!buffer_)
305                 return;
306
307         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
308
309         buffer_->text().init(this);
310         update();
311         switchKeyMap();
312 }
313
314
315 bool BufferView::fitCursor()
316 {
317         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
318                 frontend::FontMetrics const & fm =
319                         theFontMetrics(cursor_.getFont());
320                 int const asc = fm.maxAscent();
321                 int const des = fm.maxDescent();
322                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
323                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
324                         return false;
325         }
326         center();
327         return true;
328 }
329
330
331 bool BufferView::multiParSel()
332 {
333         if (!cursor_.selection())
334                 return false;
335         bool ret = multiparsel_cache_;
336         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
337         // Either this, or previous selection spans paragraphs
338         return ret || multiparsel_cache_;
339 }
340
341
342 bool BufferView::update(Update::flags flags)
343 {
344         // This is close to a hot-path.
345         if (lyxerr.debugging(Debug::DEBUG)) {
346                 lyxerr[Debug::DEBUG]
347                         << BOOST_CURRENT_FUNCTION
348                         << "[fitcursor = " << (flags & Update::FitCursor)
349                         << ", forceupdate = " << (flags & Update::Force)
350                         << ", singlepar = " << (flags & Update::SinglePar)
351                         << "]  buffer: " << buffer_ << endl;
352         }
353
354         // Check needed to survive LyX startup
355         if (!buffer_)
356                 return false;
357
358         lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
359
360         // Update macro store
361         buffer_->buildMacros();
362
363         // First drawing step
364         updateMetrics(flags & Update::SinglePar);
365
366         // The second drawing step is done in WorkArea::redraw() if needed.
367         bool const need_second_step =
368                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
369                 && (fitCursor() || multiParSel());
370
371         return need_second_step;
372 }
373
374
375 void BufferView::updateScrollbar()
376 {
377         if (!buffer_) {
378                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
379                                      << " no text in updateScrollbar" << endl;
380                 scrollbarParameters_.reset();
381                 return;
382         }
383
384         LyXText & t = buffer_->text();
385         int const parsize = int(t.paragraphs().size() - 1);
386         if (anchor_ref_ >  parsize)  {
387                 anchor_ref_ = parsize;
388                 offset_ref_ = 0;
389         }
390
391         lyxerr[Debug::GUI]
392                 << BOOST_CURRENT_FUNCTION
393                 << " Updating scrollbar: height: " << t.paragraphs().size()
394                 << " curr par: " << cursor_.bottom().pit()
395                 << " default height " << defaultRowHeight() << endl;
396
397         // It would be better to fix the scrollbar to understand
398         // values in [0..1] and divide everything by wh
399
400         // estimated average paragraph height:
401         if (wh_ == 0)
402                 wh_ = height_ / 4;
403         int h = t.getPar(anchor_ref_).height();
404
405         // Normalize anchor/offset (MV):
406         while (offset_ref_ > h && anchor_ref_ < parsize) {
407                 anchor_ref_++;
408                 offset_ref_ -= h;
409                 h = t.getPar(anchor_ref_).height();
410         }
411         // Look at paragraph heights on-screen
412         int sumh = 0;
413         int nh = 0;
414         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
415                 if (sumh > height_)
416                         break;
417                 int const h2 = t.getPar(pit).height();
418                 sumh += h2;
419                 nh++;
420         }
421
422         BOOST_ASSERT(nh);
423         int const hav = sumh / nh;
424         // More realistic average paragraph height
425         if (hav > wh_)
426                 wh_ = hav;
427
428         BOOST_ASSERT(h);
429         scrollbarParameters_.height = (parsize + 1) * wh_;
430         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
431         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
432 }
433
434
435 ScrollbarParameters const & BufferView::scrollbarParameters() const
436 {
437         return scrollbarParameters_;
438 }
439
440
441 void BufferView::scrollDocView(int value)
442 {
443         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
444                            << "[ value = " << value << "]" << endl;
445
446         if (!buffer_)
447                 return;
448
449         LyXText & t = buffer_->text();
450
451         float const bar = value / float(wh_ * t.paragraphs().size());
452
453         anchor_ref_ = int(bar * t.paragraphs().size());
454         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
455                 anchor_ref_ = int(t.paragraphs().size()) - 1;
456         t.redoParagraph(*this, anchor_ref_);
457         int const h = t.getPar(anchor_ref_).height();
458         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
459 }
460
461
462 void BufferView::setCursorFromScrollbar()
463 {
464         LyXText & t = buffer_->text();
465
466         int const height = 2 * defaultRowHeight();
467         int const first = height;
468         int const last = height_ - height;
469         LCursor & cur = cursor_;
470
471         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
472
473         switch (st) {
474         case bv_funcs::CUR_ABOVE:
475                 t.setCursorFromCoordinates(cur, 0, first);
476                 cur.clearSelection();
477                 break;
478         case bv_funcs::CUR_BELOW:
479                 t.setCursorFromCoordinates(cur, 0, last);
480                 cur.clearSelection();
481                 break;
482         case bv_funcs::CUR_INSIDE:
483                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
484                 int const newy = min(last, max(y, first));
485                 if (y != newy) {
486                         cur.reset(buffer_->inset());
487                         t.setCursorFromCoordinates(cur, 0, newy);
488                 }
489         }
490 }
491
492
493 Change const BufferView::getCurrentChange() const
494 {
495         if (!cursor_.selection())
496                 return Change(Change::UNCHANGED);
497
498         DocIterator dit = cursor_.selectionBegin();
499         return dit.paragraph().lookupChange(dit.pos());
500 }
501
502
503 void BufferView::saveBookmark(bool persistent)
504 {
505         LyX::ref().session().bookmarks().save(
506                 buffer_->fileName(),
507                 cursor_.paragraph().id(),
508                 cursor_.pos(),
509                 persistent
510         );
511         if (persistent)
512                 // emit message signal.
513                 message(_("Save bookmark"));
514 }
515
516
517 void BufferView::moveToPosition(int par_id, pos_type par_pos)
518 {
519         cursor_.clearSelection();
520
521         ParIterator par = buffer_->getParFromID(par_id);
522         if (par == buffer_->par_iterator_end())
523                 return;
524
525         setCursor(makeDocIterator(par, min(par->size(), par_pos)));
526 }
527
528
529 void BufferView::switchKeyMap()
530 {
531         if (!lyxrc.rtl_support)
532                 return;
533
534         if (getLyXText()->real_current_font.isRightToLeft()) {
535                 if (intl_->keymap == Intl::PRIMARY)
536                         intl_->keyMapSec();
537         } else {
538                 if (intl_->keymap == Intl::SECONDARY)
539                         intl_->keyMapPrim();
540         }
541 }
542
543
544 int BufferView::workWidth() const
545 {
546         return width_;
547 }
548
549
550 void BufferView::center()
551 {
552         CursorSlice & bot = cursor_.bottom();
553         pit_type const pit = bot.pit();
554         bot.text()->redoParagraph(*this, pit);
555         Paragraph const & par = bot.text()->paragraphs()[pit];
556         anchor_ref_ = pit;
557         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
558                 + par.ascent() - height_ / 2;
559 }
560
561
562 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
563 {
564         FuncStatus flag;
565
566         switch (cmd.action) {
567
568         case LFUN_UNDO:
569                 flag.enabled(!buffer_->undostack().empty());
570                 break;
571         case LFUN_REDO:
572                 flag.enabled(!buffer_->redostack().empty());
573                 break;
574         case LFUN_FILE_INSERT:
575         case LFUN_FILE_INSERT_ASCII_PARA:
576         case LFUN_FILE_INSERT_ASCII:
577         case LFUN_BOOKMARK_SAVE:
578                 // FIXME: Actually, these LFUNS should be moved to LyXText
579                 flag.enabled(cursor_.inTexted());
580                 break;
581         case LFUN_FONT_STATE:
582         case LFUN_LABEL_INSERT:
583         case LFUN_PARAGRAPH_GOTO:
584         // FIXME handle non-trivially
585         case LFUN_OUTLINE_UP:
586         case LFUN_OUTLINE_DOWN:
587         case LFUN_OUTLINE_IN:
588         case LFUN_OUTLINE_OUT:
589         case LFUN_NOTE_NEXT:
590         case LFUN_REFERENCE_NEXT:
591         case LFUN_WORD_FIND:
592         case LFUN_WORD_REPLACE:
593         case LFUN_MARK_OFF:
594         case LFUN_MARK_ON:
595         case LFUN_MARK_TOGGLE:
596         case LFUN_SCREEN_RECENTER:
597         case LFUN_BIBTEX_DATABASE_ADD:
598         case LFUN_BIBTEX_DATABASE_DEL:
599         case LFUN_WORDS_COUNT:
600         case LFUN_NEXT_INSET_TOGGLE:
601                 flag.enabled(true);
602                 break;
603
604         case LFUN_LABEL_GOTO: {
605                 flag.enabled(!cmd.argument().empty()
606                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
607                 break;
608         }
609
610         case LFUN_CHANGES_TRACK:
611                 flag.enabled(true);
612                 flag.setOnOff(buffer_->params().trackChanges);
613                 break;
614
615         case LFUN_CHANGES_OUTPUT: {
616                 OutputParams runparams;
617                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
618                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
619                 flag.setOnOff(buffer_->params().outputChanges);
620                 break;
621         }
622
623         case LFUN_CHANGES_MERGE:
624         case LFUN_CHANGE_NEXT:
625         case LFUN_ALL_CHANGES_ACCEPT:
626         case LFUN_ALL_CHANGES_REJECT:
627                 flag.enabled(buffer_); // FIXME: Change tracking (MG)
628                 break;
629
630         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
631                 flag.setOnOff(buffer_->params().compressed);
632                 break;
633         }
634
635         default:
636                 flag.enabled(false);
637         }
638
639         return flag;
640 }
641
642
643 bool BufferView::dispatch(FuncRequest const & cmd)
644 {
645         //lyxerr << BOOST_CURRENT_FUNCTION
646         //       << [ cmd = " << cmd << "]" << endl;
647
648         // Make sure that the cached BufferView is correct.
649         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
650                 << " action[" << cmd.action << ']'
651                 << " arg[" << to_utf8(cmd.argument()) << ']'
652                 << " x[" << cmd.x << ']'
653                 << " y[" << cmd.y << ']'
654                 << " button[" << cmd.button() << ']'
655                 << endl;
656
657         LCursor & cur = cursor_;
658
659         switch (cmd.action) {
660
661         case LFUN_UNDO:
662                 if (buffer_) {
663                         cur.message(_("Undo"));
664                         cur.clearSelection();
665                         if (!textUndo(*this))
666                                 cur.message(_("No further undo information"));
667                         update();
668                         switchKeyMap();
669                 }
670                 break;
671
672         case LFUN_REDO:
673                 if (buffer_) {
674                         cur.message(_("Redo"));
675                         cur.clearSelection();
676                         if (!textRedo(*this))
677                                 cur.message(_("No further redo information"));
678                         update();
679                         switchKeyMap();
680                 }
681                 break;
682
683         case LFUN_FILE_INSERT:
684                 // FIXME: We don't know the encoding of filenames
685                 menuInsertLyXFile(to_utf8(cmd.argument()));
686                 break;
687
688         case LFUN_FILE_INSERT_ASCII_PARA:
689                 // FIXME: We don't know the encoding of filenames
690                 insertAsciiFile(this, to_utf8(cmd.argument()), true);
691                 break;
692
693         case LFUN_FILE_INSERT_ASCII:
694                 // FIXME: We don't know the encoding of filenames
695                 insertAsciiFile(this, to_utf8(cmd.argument()), false);
696                 break;
697
698         case LFUN_FONT_STATE:
699                 cur.message(from_utf8(cur.currentState()));
700                 break;
701
702         case LFUN_BOOKMARK_SAVE:
703                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
704                 break;
705
706         case LFUN_LABEL_GOTO: {
707                 docstring label = cmd.argument();
708                 if (label.empty()) {
709                         InsetRef * inset =
710                                 getInsetByCode<InsetRef>(cursor_,
711                                                          InsetBase::REF_CODE);
712                         if (inset) {
713                                 label = inset->getParam("reference");
714                                 // persistent=false: use temp_bookmark
715                                 saveBookmark(false);
716                         }
717                 }
718
719                 if (!label.empty())
720                         gotoLabel(label);
721                 break;
722         }
723
724         case LFUN_PARAGRAPH_GOTO: {
725                 int const id = convert<int>(to_utf8(cmd.argument()));
726                 ParIterator par = buffer_->getParFromID(id);
727                 if (par == buffer_->par_iterator_end()) {
728                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
729                                             << id << ']' << endl;
730                         break;
731                 } else {
732                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
733                                             << " found." << endl;
734                 }
735
736                 // Set the cursor
737                 setCursor(makeDocIterator(par, 0));
738
739                 update();
740                 switchKeyMap();
741                 break;
742         }
743
744         case LFUN_OUTLINE_UP:
745                 toc::outline(toc::Up, cursor_);
746                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
747                 updateLabels(*buffer_);
748                 break;
749         case LFUN_OUTLINE_DOWN:
750                 toc::outline(toc::Down, cursor_);
751                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
752                 updateLabels(*buffer_);
753                 break;
754         case LFUN_OUTLINE_IN:
755                 toc::outline(toc::In, cursor_);
756                 updateLabels(*buffer_);
757                 break;
758         case LFUN_OUTLINE_OUT:
759                 toc::outline(toc::Out, cursor_);
760                 updateLabels(*buffer_);
761                 break;
762
763         case LFUN_NOTE_NEXT:
764                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
765                 break;
766
767         case LFUN_REFERENCE_NEXT: {
768                 vector<InsetBase_code> tmp;
769                 tmp.push_back(InsetBase::LABEL_CODE);
770                 tmp.push_back(InsetBase::REF_CODE);
771                 bv_funcs::gotoInset(this, tmp, true);
772                 break;
773         }
774
775         case LFUN_CHANGES_TRACK:
776                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
777                 break;
778
779         case LFUN_CHANGES_OUTPUT: {
780                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
781                 break;
782         }
783
784         case LFUN_CHANGE_NEXT:
785                 findNextChange(this);
786                 break;
787
788         case LFUN_CHANGES_MERGE:
789                 if (findNextChange(this))
790                         showDialog("changes");
791                 break;
792
793         case LFUN_ALL_CHANGES_ACCEPT: {
794                 cursor_.reset(buffer_->inset());
795 #ifdef WITH_WARNINGS
796 #warning FIXME changes
797 #endif
798                 while (findNextChange(this))
799                         getLyXText()->acceptChange(cursor_);
800                 update();
801                 break;
802         }
803
804         case LFUN_ALL_CHANGES_REJECT: {
805                 cursor_.reset(buffer_->inset());
806 #ifdef WITH_WARNINGS
807 #warning FIXME changes
808 #endif
809                 while (findNextChange(this))
810                         getLyXText()->rejectChange(cursor_);
811                 break;
812         }
813
814         case LFUN_WORD_FIND:
815                 find(this, cmd);
816                 break;
817
818         case LFUN_WORD_REPLACE:
819                 replace(this, cmd);
820                 break;
821
822         case LFUN_MARK_OFF:
823                 cur.clearSelection();
824                 cur.resetAnchor();
825                 cur.message(from_utf8(N_("Mark off")));
826                 break;
827
828         case LFUN_MARK_ON:
829                 cur.clearSelection();
830                 cur.mark() = true;
831                 cur.resetAnchor();
832                 cur.message(from_utf8(N_("Mark on")));
833                 break;
834
835         case LFUN_MARK_TOGGLE:
836                 cur.clearSelection();
837                 if (cur.mark()) {
838                         cur.mark() = false;
839                         cur.message(from_utf8(N_("Mark removed")));
840                 } else {
841                         cur.mark() = true;
842                         cur.message(from_utf8(N_("Mark set")));
843                 }
844                 cur.resetAnchor();
845                 break;
846
847         case LFUN_SCREEN_RECENTER:
848                 center();
849                 break;
850
851         case LFUN_BIBTEX_DATABASE_ADD: {
852                 LCursor tmpcur = cursor_;
853                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
854                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
855                                                 InsetBase::BIBTEX_CODE);
856                 if (inset) {
857                         if (inset->addDatabase(to_utf8(cmd.argument())))
858                                 buffer_->updateBibfilesCache();
859                 }
860                 break;
861         }
862
863         case LFUN_BIBTEX_DATABASE_DEL: {
864                 LCursor tmpcur = cursor_;
865                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
866                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
867                                                 InsetBase::BIBTEX_CODE);
868                 if (inset) {
869                         if (inset->delDatabase(to_utf8(cmd.argument())))
870                                 buffer_->updateBibfilesCache();
871                 }
872                 break;
873         }
874
875         case LFUN_WORDS_COUNT: {
876                 DocIterator from, to;
877                 if (cur.selection()) {
878                         from = cur.selectionBegin();
879                         to = cur.selectionEnd();
880                 } else {
881                         from = doc_iterator_begin(buffer_->inset());
882                         to = doc_iterator_end(buffer_->inset());
883                 }
884                 int const count = countWords(from, to);
885                 docstring message;
886                 if (count != 1) {
887                         if (cur.selection())
888                                 message = bformat(_("%1$d words in selection."),
889                                           count);
890                                 else
891                                         message = bformat(_("%1$d words in document."),
892                                                           count);
893                 }
894                 else {
895                         if (cur.selection())
896                                 message = _("One word in selection.");
897                         else
898                                 message = _("One word in document.");
899                 }
900
901                 Alert::information(_("Count words"), message);
902         }
903                 break;
904
905         case LFUN_BUFFER_TOGGLE_COMPRESSION:
906                 // turn compression on/off
907                 buffer_->params().compressed = !buffer_->params().compressed;
908                 break;
909
910         case LFUN_NEXT_INSET_TOGGLE: {
911                 // this is the real function we want to invoke
912                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
913                 // if there is an inset at cursor, see whether it
914                 // wants to toggle.
915                 InsetBase * inset = cur.nextInset();
916                 if (inset && inset->isActive()) {
917                         LCursor tmpcur = cur;
918                         tmpcur.pushLeft(*inset);
919                         inset->dispatch(tmpcur, tmpcmd);
920                         if (tmpcur.result().dispatched()) {
921                                 cur.dispatched();
922                         }
923                 }
924                 // if it did not work, try the underlying inset.
925                 if (!cur.result().dispatched())
926                         cur.dispatch(tmpcmd);
927
928                 if (cur.result().dispatched())
929                         cur.clearSelection();
930
931                 break;
932         }
933
934         default:
935                 return false;
936         }
937
938         return true;
939 }
940
941
942 docstring const BufferView::requestSelection()
943 {
944         if (!buffer_)
945                 return docstring();
946
947         LCursor & cur = cursor_;
948
949         if (!cur.selection()) {
950                 xsel_cache_.set = false;
951                 return docstring();
952         }
953
954         if (!xsel_cache_.set ||
955             cur.top() != xsel_cache_.cursor ||
956             cur.anchor_.top() != xsel_cache_.anchor)
957         {
958                 xsel_cache_.cursor = cur.top();
959                 xsel_cache_.anchor = cur.anchor_.top();
960                 xsel_cache_.set = cur.selection();
961                 return cur.selectionAsString(false);
962         }
963         return docstring();
964 }
965
966
967 void BufferView::clearSelection()
968 {
969         if (buffer_) {
970                 cursor_.clearSelection();
971                 xsel_cache_.set = false;
972         }
973 }
974
975
976 void BufferView::workAreaResize(int width, int height)
977 {
978         bool const widthChange = width != width_;
979         bool const heightChange = height != height_;
980
981         // Update from work area
982         width_ = width;
983         height_ = height;
984
985         if (buffer_)
986                 resize();
987
988         update();
989 }
990
991
992 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
993 {
994         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
995
996         // This is only called for mouse related events including
997         // LFUN_FILE_OPEN generated by drag-and-drop.
998         FuncRequest cmd = cmd0;
999
1000         if (!buffer_)
1001                 return false;
1002
1003         LCursor cur(*this);
1004         cur.push(buffer_->inset());
1005         cur.selection() = cursor_.selection();
1006
1007         // Doesn't go through lyxfunc, so we need to update
1008         // the layout choice etc. ourselves
1009
1010         // E.g. Qt mouse press when no buffer
1011         if (!buffer_)
1012                 return false;
1013
1014         // Either the inset under the cursor or the
1015         // surrounding LyXText will handle this event.
1016
1017         // Build temporary cursor.
1018         cmd.y = min(max(cmd.y, -1), height_);
1019         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1020         //lyxerr << BOOST_CURRENT_FUNCTION
1021         //       << " * hit inset at tip: " << inset << endl;
1022         //lyxerr << BOOST_CURRENT_FUNCTION
1023         //       << " * created temp cursor:" << cur << endl;
1024
1025         // Put anchor at the same position.
1026         cur.resetAnchor();
1027
1028         // Try to dispatch to an non-editable inset near this position
1029         // via the temp cursor. If the inset wishes to change the real
1030         // cursor it has to do so explicitly by using
1031         //  cur.bv().cursor() = cur;  (or similar)
1032         if (inset)
1033                 inset->dispatch(cur, cmd);
1034
1035         // Now dispatch to the temporary cursor. If the real cursor should
1036         // be modified, the inset's dispatch has to do so explicitly.
1037         if (!cur.result().dispatched())
1038                 cur.dispatch(cmd);
1039
1040         if (cur.result().dispatched()) {
1041                 // Redraw if requested or necessary.
1042                 if (cur.result().update())
1043                         update(Update::FitCursor | Update::Force);
1044                 else
1045                         update(Update::FitCursor | Update::MultiParSel);
1046         }
1047
1048         return true;
1049 }
1050
1051
1052 void BufferView::scroll(int /*lines*/)
1053 {
1054 //      if (!buffer_)
1055 //              return;
1056 //
1057 //      LyXText const * t = &buffer_->text();
1058 //      int const line_height = defaultRowHeight();
1059 //
1060 //      // The new absolute coordinate
1061 //      int new_top_y = top_y() + lines * line_height;
1062 //
1063 //      // Restrict to a valid value
1064 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1065 //      new_top_y = std::max(0, new_top_y);
1066 //
1067 //      scrollDocView(new_top_y);
1068 //
1069 //      // Update the scrollbar.
1070 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1071 }
1072
1073
1074 void BufferView::setCursorFromRow(int row)
1075 {
1076         int tmpid = -1;
1077         int tmppos = -1;
1078
1079         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1080
1081         if (tmpid == -1)
1082                 buffer_->text().setCursor(cursor_, 0, 0);
1083         else
1084                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1085 }
1086
1087
1088 void BufferView::gotoLabel(docstring const & label)
1089 {
1090         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1091                 vector<docstring> labels;
1092                 it->getLabelList(*buffer_, labels);
1093                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1094                         setCursor(it);
1095                         update();
1096                         return;
1097                 }
1098         }
1099 }
1100
1101
1102 LyXText * BufferView::getLyXText()
1103 {
1104         LyXText * text = cursor_.innerText();
1105         BOOST_ASSERT(text);
1106         return text;
1107 }
1108
1109
1110 LyXText const * BufferView::getLyXText() const
1111 {
1112         LyXText const * text = cursor_.innerText();
1113         BOOST_ASSERT(text);
1114         return text;
1115 }
1116
1117
1118 int BufferView::workHeight() const
1119 {
1120         return height_;
1121 }
1122
1123
1124 void BufferView::setCursor(DocIterator const & dit)
1125 {
1126         size_t const n = dit.depth();
1127         for (size_t i = 0; i < n; ++i)
1128                 dit[i].inset().edit(cursor_, true);
1129
1130         cursor_.setCursor(dit);
1131         cursor_.selection() = false;
1132 }
1133
1134
1135 void BufferView::mouseSetCursor(LCursor & cur)
1136 {
1137         BOOST_ASSERT(&cur.bv() == this);
1138
1139         // Has the cursor just left the inset?
1140         bool badcursor = false;
1141         if (&cursor_.inset() != &cur.inset())
1142                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1143
1144         // do the dEPM magic if needed
1145         // FIXME: move this to InsetText::notifyCursorLeaves?
1146         if (!badcursor && cursor_.inTexted())
1147                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1148
1149         cursor_ = cur;
1150         cursor_.clearSelection();
1151         cursor_.setTargetX();
1152         finishUndo();
1153
1154 }
1155
1156
1157 void BufferView::putSelectionAt(DocIterator const & cur,
1158                                 int length, bool backwards)
1159 {
1160         cursor_.clearSelection();
1161
1162         setCursor(cur);
1163
1164         if (length) {
1165                 if (backwards) {
1166                         cursor_.pos() += length;
1167                         cursor_.setSelection(cursor_, -length);
1168                 } else
1169                         cursor_.setSelection(cursor_, length);
1170         }
1171 }
1172
1173
1174 LCursor & BufferView::cursor()
1175 {
1176         return cursor_;
1177 }
1178
1179
1180 LCursor const & BufferView::cursor() const
1181 {
1182         return cursor_;
1183 }
1184
1185
1186 pit_type BufferView::anchor_ref() const
1187 {
1188         return anchor_ref_;
1189 }
1190
1191
1192 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1193 {
1194         return metrics_info_;
1195 }
1196
1197
1198 void BufferView::updateMetrics(bool singlepar)
1199 {
1200         // FIXME (Abdel 19/10/2006):
1201         // There's something fishy in tabular. The coord_cache_ is not
1202         // correctly reconstructed when a character is trying to be inserted.
1203         // Not clearing out the coord_cache_ fixes the crash but there is a
1204         // bad side effect: buffer-begin and buffer-end do not update the screen.
1205         //
1206         // Remove old position cache
1207         coord_cache_.clear();
1208
1209         LyXText & buftext = buffer_->text();
1210         pit_type size = int(buftext.paragraphs().size());
1211
1212         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1213                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1214                 offset_ref_ = 0;
1215         }
1216
1217         pit_type const pit = anchor_ref_;
1218         int pit1 = pit;
1219         int pit2 = pit;
1220         size_t const npit = buftext.paragraphs().size();
1221
1222         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1223         // the (main text, not inset!) paragraph containing the cursor.
1224         // (if this paragraph contains insets etc., rebreaking will
1225         // recursively descend)
1226         if (!singlepar || pit == cursor_.bottom().pit())
1227                 buftext.redoParagraph(*this, pit);
1228         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1229
1230         // Redo paragraphs above anchor if necessary; again, in Single Par
1231         // mode, only if we encounter the (main text) one having the cursor.
1232         int y1 = y0;
1233         while (y1 > 0 && pit1 > 0) {
1234                 y1 -= buftext.getPar(pit1).ascent();
1235                 --pit1;
1236                 if (!singlepar || pit1 == cursor_.bottom().pit())
1237                         buftext.redoParagraph(*this, pit1);
1238                 y1 -= buftext.getPar(pit1).descent();
1239         }
1240
1241
1242         // Take care of ascent of first line
1243         y1 -= buftext.getPar(pit1).ascent();
1244
1245         // Normalize anchor for next time
1246         anchor_ref_ = pit1;
1247         offset_ref_ = -y1;
1248
1249         // Grey at the beginning is ugly
1250         if (pit1 == 0 && y1 > 0) {
1251                 y0 -= y1;
1252                 y1 = 0;
1253                 anchor_ref_ = 0;
1254         }
1255
1256         // Redo paragraphs below the anchor if necessary. Single par mode:
1257         // only the one containing the cursor if encountered.
1258         int y2 = y0;
1259         while (y2 < height_ && pit2 < int(npit) - 1) {
1260                 y2 += buftext.getPar(pit2).descent();
1261                 ++pit2;
1262                 if (!singlepar || pit2 == cursor_.bottom().pit())
1263                         buftext.redoParagraph(*this, pit2);
1264                 y2 += buftext.getPar(pit2).ascent();
1265         }
1266
1267         // Take care of descent of last line
1268         y2 += buftext.getPar(pit2).descent();
1269
1270         // The coordinates of all these paragraphs are correct, cache them
1271         int y = y1;
1272         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1273         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1274                 Paragraph const & par = buftext.getPar(pit);
1275                 y += par.ascent();
1276                 parPos[pit] = Point(0, y);
1277                 if (singlepar && pit == cursor_.bottom().pit()) {
1278                         // In Single Paragraph mode, collect here the
1279                         // y1 and y2 of the (one) paragraph the cursor is in
1280                         y1 = y - par.ascent();
1281                         y2 = y + par.descent();
1282                 }
1283                 y += par.descent();
1284         }
1285
1286         if (singlepar) {
1287                 // collect cursor paragraph iter bounds
1288                 pit1 = cursor_.bottom().pit();
1289                 pit2 = cursor_.bottom().pit();
1290         }
1291
1292         lyxerr[Debug::DEBUG]
1293                 << BOOST_CURRENT_FUNCTION
1294                 << " y1: " << y1
1295                 << " y2: " << y2
1296                 << " pit1: " << pit1
1297                 << " pit2: " << pit2
1298                 << " npit: " << npit
1299                 << " singlepar: " << singlepar
1300                 << "size: " << size
1301                 << endl;
1302
1303         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1304
1305         if (lyxerr.debugging(Debug::WORKAREA)) {
1306                 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1307                 coord_cache_.dump();
1308         }
1309 }
1310
1311
1312 void BufferView::menuInsertLyXFile(string const & filenm)
1313 {
1314         BOOST_ASSERT(cursor_.inTexted());
1315         string filename = filenm;
1316
1317         if (filename.empty()) {
1318                 // Launch a file browser
1319                 // FIXME UNICODE
1320                 string initpath = lyxrc.document_path;
1321
1322                 if (buffer_) {
1323                         string const trypath = buffer_->filePath();
1324                         // If directory is writeable, use this as default.
1325                         if (isDirWriteable(trypath))
1326                                 initpath = trypath;
1327                 }
1328
1329                 // FIXME UNICODE
1330                 FileDialog fileDlg(_("Select LyX document to insert"),
1331                         LFUN_FILE_INSERT,
1332                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1333                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1334
1335                 FileDialog::Result result =
1336                         fileDlg.open(from_utf8(initpath),
1337                                      FileFilterList(_("LyX Documents (*.lyx)")),
1338                                      docstring());
1339
1340                 if (result.first == FileDialog::Later)
1341                         return;
1342
1343                 // FIXME UNICODE
1344                 filename = to_utf8(result.second);
1345
1346                 // check selected filename
1347                 if (filename.empty()) {
1348                         // emit message signal.
1349                         message(_("Canceled."));
1350                         return;
1351                 }
1352         }
1353
1354         // Get absolute path of file and add ".lyx"
1355         // to the filename if necessary
1356         filename = fileSearch(string(), filename, "lyx");
1357
1358         docstring const disp_fn = makeDisplayPath(filename);
1359         // emit message signal.
1360         message(bformat(_("Inserting document %1$s..."), disp_fn));
1361
1362         docstring res;
1363         Buffer buf("", false);
1364         if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1365                 ErrorList & el = buffer_->errorList("Parse");
1366                 // Copy the inserted document error list into the current buffer one.
1367                 el = buf.errorList("Parse");
1368                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1369                                              buf.params().textclass, el);
1370                 res = _("Document %1$s inserted.");
1371         } else
1372                 res = _("Could not insert document %1$s");
1373
1374         // emit message signal.
1375         message(bformat(res, disp_fn));
1376         buffer_->errors("Parse");
1377         resize();
1378 }
1379
1380
1381 } // namespace lyx