]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
Fix bugs 1720 (almost) and 2877
[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         if (lyxerr.debugging(Debug::WORKAREA)) {
359                 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
360         }
361
362         // Update macro store
363         buffer_->buildMacros();
364
365         // First drawing step
366         updateMetrics(flags & Update::SinglePar);
367
368         // The second drawing step is done in WorkArea::redraw() if needed.
369         bool const need_second_step =
370                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
371                 && (fitCursor() || multiParSel());
372
373         return need_second_step;
374 }
375
376
377 void BufferView::updateScrollbar()
378 {
379         if (!buffer_) {
380                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
381                                      << " no text in updateScrollbar" << endl;
382                 scrollbarParameters_.reset();
383                 return;
384         }
385
386         LyXText & t = buffer_->text();
387         int const parsize = int(t.paragraphs().size() - 1);
388         if (anchor_ref_ >  parsize)  {
389                 anchor_ref_ = parsize;
390                 offset_ref_ = 0;
391         }
392
393         if (lyxerr.debugging(Debug::GUI)) {
394                 lyxerr[Debug::GUI]
395                         << BOOST_CURRENT_FUNCTION
396                         << " Updating scrollbar: height: " << t.paragraphs().size()
397                         << " curr par: " << cursor_.bottom().pit()
398                         << " default height " << defaultRowHeight() << endl;
399         }
400
401         // It would be better to fix the scrollbar to understand
402         // values in [0..1] and divide everything by wh
403
404         // estimated average paragraph height:
405         if (wh_ == 0)
406                 wh_ = height_ / 4;
407         int h = t.getPar(anchor_ref_).height();
408
409         // Normalize anchor/offset (MV):
410         while (offset_ref_ > h && anchor_ref_ < parsize) {
411                 anchor_ref_++;
412                 offset_ref_ -= h;
413                 h = t.getPar(anchor_ref_).height();
414         }
415         // Look at paragraph heights on-screen
416         int sumh = 0;
417         int nh = 0;
418         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
419                 if (sumh > height_)
420                         break;
421                 int const h2 = t.getPar(pit).height();
422                 sumh += h2;
423                 nh++;
424         }
425
426         BOOST_ASSERT(nh);
427         int const hav = sumh / nh;
428         // More realistic average paragraph height
429         if (hav > wh_)
430                 wh_ = hav;
431
432         BOOST_ASSERT(h);
433         scrollbarParameters_.height = (parsize + 1) * wh_;
434         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
435         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
436 }
437
438
439 ScrollbarParameters const & BufferView::scrollbarParameters() const
440 {
441         return scrollbarParameters_;
442 }
443
444
445 void BufferView::scrollDocView(int value)
446 {
447         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
448                            << "[ value = " << value << "]" << endl;
449
450         if (!buffer_)
451                 return;
452
453         LyXText & t = buffer_->text();
454
455         float const bar = value / float(wh_ * t.paragraphs().size());
456
457         anchor_ref_ = int(bar * t.paragraphs().size());
458         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
459                 anchor_ref_ = int(t.paragraphs().size()) - 1;
460         t.redoParagraph(*this, anchor_ref_);
461         int const h = t.getPar(anchor_ref_).height();
462         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
463 }
464
465
466 void BufferView::setCursorFromScrollbar()
467 {
468         LyXText & t = buffer_->text();
469
470         int const height = 2 * defaultRowHeight();
471         int const first = height;
472         int const last = height_ - height;
473         LCursor & cur = cursor_;
474
475         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
476
477         switch (st) {
478         case bv_funcs::CUR_ABOVE:
479                 t.setCursorFromCoordinates(cur, 0, first);
480                 cur.clearSelection();
481                 break;
482         case bv_funcs::CUR_BELOW:
483                 t.setCursorFromCoordinates(cur, 0, last);
484                 cur.clearSelection();
485                 break;
486         case bv_funcs::CUR_INSIDE:
487                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
488                 int const newy = min(last, max(y, first));
489                 if (y != newy) {
490                         cur.reset(buffer_->inset());
491                         t.setCursorFromCoordinates(cur, 0, newy);
492                 }
493         }
494 }
495
496
497 Change const BufferView::getCurrentChange() const
498 {
499         if (!cursor_.selection())
500                 return Change(Change::UNCHANGED);
501
502         DocIterator dit = cursor_.selectionBegin();
503         return dit.paragraph().lookupChange(dit.pos());
504 }
505
506
507 void BufferView::saveBookmark(bool persistent)
508 {
509         LyX::ref().session().bookmarks().save(
510                 buffer_->fileName(),
511                 cursor_.paragraph().id(),
512                 cursor_.pos(),
513                 persistent
514         );
515         if (persistent)
516                 // emit message signal.
517                 message(_("Save bookmark"));
518 }
519
520
521 void BufferView::moveToPosition(int par_id, pos_type par_pos)
522 {
523         cursor_.clearSelection();
524
525         ParIterator par = buffer_->getParFromID(par_id);
526         if (par == buffer_->par_iterator_end())
527                 return;
528
529         setCursor(makeDocIterator(par, min(par->size(), par_pos)));
530 }
531
532
533 void BufferView::switchKeyMap()
534 {
535         if (!lyxrc.rtl_support)
536                 return;
537
538         if (getLyXText()->real_current_font.isRightToLeft()) {
539                 if (intl_->keymap == Intl::PRIMARY)
540                         intl_->keyMapSec();
541         } else {
542                 if (intl_->keymap == Intl::SECONDARY)
543                         intl_->keyMapPrim();
544         }
545 }
546
547
548 int BufferView::workWidth() const
549 {
550         return width_;
551 }
552
553
554 void BufferView::center()
555 {
556         CursorSlice & bot = cursor_.bottom();
557         pit_type const pit = bot.pit();
558         bot.text()->redoParagraph(*this, pit);
559         Paragraph const & par = bot.text()->paragraphs()[pit];
560         anchor_ref_ = pit;
561         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
562                 + par.ascent() - height_ / 2;
563 }
564
565
566 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
567 {
568         FuncStatus flag;
569
570         switch (cmd.action) {
571
572         case LFUN_UNDO:
573                 flag.enabled(!buffer_->undostack().empty());
574                 break;
575         case LFUN_REDO:
576                 flag.enabled(!buffer_->redostack().empty());
577                 break;
578         case LFUN_FILE_INSERT:
579         case LFUN_FILE_INSERT_ASCII_PARA:
580         case LFUN_FILE_INSERT_ASCII:
581         case LFUN_BOOKMARK_SAVE:
582                 // FIXME: Actually, these LFUNS should be moved to LyXText
583                 flag.enabled(cursor_.inTexted());
584                 break;
585         case LFUN_FONT_STATE:
586         case LFUN_LABEL_INSERT:
587         case LFUN_PARAGRAPH_GOTO:
588         // FIXME handle non-trivially
589         case LFUN_OUTLINE_UP:
590         case LFUN_OUTLINE_DOWN:
591         case LFUN_OUTLINE_IN:
592         case LFUN_OUTLINE_OUT:
593         case LFUN_NOTE_NEXT:
594         case LFUN_REFERENCE_NEXT:
595         case LFUN_WORD_FIND:
596         case LFUN_WORD_REPLACE:
597         case LFUN_MARK_OFF:
598         case LFUN_MARK_ON:
599         case LFUN_MARK_TOGGLE:
600         case LFUN_SCREEN_RECENTER:
601         case LFUN_BIBTEX_DATABASE_ADD:
602         case LFUN_BIBTEX_DATABASE_DEL:
603         case LFUN_WORDS_COUNT:
604         case LFUN_NEXT_INSET_TOGGLE:
605                 flag.enabled(true);
606                 break;
607
608         case LFUN_LABEL_GOTO: {
609                 flag.enabled(!cmd.argument().empty()
610                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
611                 break;
612         }
613
614         case LFUN_CHANGES_TRACK:
615                 flag.enabled(true);
616                 flag.setOnOff(buffer_->params().trackChanges);
617                 break;
618
619         case LFUN_CHANGES_OUTPUT: {
620                 OutputParams runparams;
621                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
622                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
623                 flag.setOnOff(buffer_->params().outputChanges);
624                 break;
625         }
626
627         case LFUN_CHANGES_MERGE:
628         case LFUN_CHANGE_NEXT:
629         case LFUN_ALL_CHANGES_ACCEPT:
630         case LFUN_ALL_CHANGES_REJECT:
631                 flag.enabled(buffer_); // FIXME: Change tracking (MG)
632                 break;
633
634         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
635                 flag.setOnOff(buffer_->params().compressed);
636                 break;
637         }
638
639         default:
640                 flag.enabled(false);
641         }
642
643         return flag;
644 }
645
646
647 bool BufferView::dispatch(FuncRequest const & cmd)
648 {
649         //lyxerr << BOOST_CURRENT_FUNCTION
650         //       << [ cmd = " << cmd << "]" << endl;
651
652         // Make sure that the cached BufferView is correct.
653         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
654                 << " action[" << cmd.action << ']'
655                 << " arg[" << to_utf8(cmd.argument()) << ']'
656                 << " x[" << cmd.x << ']'
657                 << " y[" << cmd.y << ']'
658                 << " button[" << cmd.button() << ']'
659                 << endl;
660
661         LCursor & cur = cursor_;
662
663         switch (cmd.action) {
664
665         case LFUN_UNDO:
666                 if (buffer_) {
667                         cur.message(_("Undo"));
668                         cur.clearSelection();
669                         if (!textUndo(*this))
670                                 cur.message(_("No further undo information"));
671                         update();
672                         switchKeyMap();
673                 }
674                 break;
675
676         case LFUN_REDO:
677                 if (buffer_) {
678                         cur.message(_("Redo"));
679                         cur.clearSelection();
680                         if (!textRedo(*this))
681                                 cur.message(_("No further redo information"));
682                         update();
683                         switchKeyMap();
684                 }
685                 break;
686
687         case LFUN_FILE_INSERT:
688                 // FIXME: We don't know the encoding of filenames
689                 menuInsertLyXFile(to_utf8(cmd.argument()));
690                 break;
691
692         case LFUN_FILE_INSERT_ASCII_PARA:
693                 // FIXME: We don't know the encoding of filenames
694                 insertAsciiFile(this, to_utf8(cmd.argument()), true);
695                 break;
696
697         case LFUN_FILE_INSERT_ASCII:
698                 // FIXME: We don't know the encoding of filenames
699                 insertAsciiFile(this, to_utf8(cmd.argument()), false);
700                 break;
701
702         case LFUN_FONT_STATE:
703                 cur.message(from_utf8(cur.currentState()));
704                 break;
705
706         case LFUN_BOOKMARK_SAVE:
707                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
708                 break;
709
710         case LFUN_LABEL_GOTO: {
711                 docstring label = cmd.argument();
712                 if (label.empty()) {
713                         InsetRef * inset =
714                                 getInsetByCode<InsetRef>(cursor_,
715                                                          InsetBase::REF_CODE);
716                         if (inset) {
717                                 label = inset->getParam("reference");
718                                 // persistent=false: use temp_bookmark
719                                 saveBookmark(false);
720                         }
721                 }
722
723                 if (!label.empty())
724                         gotoLabel(label);
725                 break;
726         }
727
728         case LFUN_PARAGRAPH_GOTO: {
729                 int const id = convert<int>(to_utf8(cmd.argument()));
730                 ParIterator par = buffer_->getParFromID(id);
731                 if (par == buffer_->par_iterator_end()) {
732                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
733                                             << id << ']' << endl;
734                         break;
735                 } else {
736                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
737                                             << " found." << endl;
738                 }
739
740                 // Set the cursor
741                 setCursor(makeDocIterator(par, 0));
742
743                 update();
744                 switchKeyMap();
745                 break;
746         }
747
748         case LFUN_OUTLINE_UP:
749                 toc::outline(toc::Up, cursor_);
750                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
751                 updateLabels(*buffer_);
752                 break;
753         case LFUN_OUTLINE_DOWN:
754                 toc::outline(toc::Down, cursor_);
755                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
756                 updateLabels(*buffer_);
757                 break;
758         case LFUN_OUTLINE_IN:
759                 toc::outline(toc::In, cursor_);
760                 updateLabels(*buffer_);
761                 break;
762         case LFUN_OUTLINE_OUT:
763                 toc::outline(toc::Out, cursor_);
764                 updateLabels(*buffer_);
765                 break;
766
767         case LFUN_NOTE_NEXT:
768                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
769                 break;
770
771         case LFUN_REFERENCE_NEXT: {
772                 vector<InsetBase_code> tmp;
773                 tmp.push_back(InsetBase::LABEL_CODE);
774                 tmp.push_back(InsetBase::REF_CODE);
775                 bv_funcs::gotoInset(this, tmp, true);
776                 break;
777         }
778
779         case LFUN_CHANGES_TRACK:
780                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
781                 break;
782
783         case LFUN_CHANGES_OUTPUT: {
784                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
785                 break;
786         }
787
788         case LFUN_CHANGE_NEXT:
789                 findNextChange(this);
790                 break;
791
792         case LFUN_CHANGES_MERGE:
793                 if (findNextChange(this))
794                         showDialog("changes");
795                 break;
796
797         case LFUN_ALL_CHANGES_ACCEPT: {
798                 cursor_.reset(buffer_->inset());
799 #ifdef WITH_WARNINGS
800 #warning FIXME changes
801 #endif
802                 while (findNextChange(this))
803                         getLyXText()->acceptChange(cursor_);
804                 update();
805                 break;
806         }
807
808         case LFUN_ALL_CHANGES_REJECT: {
809                 cursor_.reset(buffer_->inset());
810 #ifdef WITH_WARNINGS
811 #warning FIXME changes
812 #endif
813                 while (findNextChange(this))
814                         getLyXText()->rejectChange(cursor_);
815                 break;
816         }
817
818         case LFUN_WORD_FIND:
819                 find(this, cmd);
820                 break;
821
822         case LFUN_WORD_REPLACE:
823                 replace(this, cmd);
824                 break;
825
826         case LFUN_MARK_OFF:
827                 cur.clearSelection();
828                 cur.resetAnchor();
829                 cur.message(from_utf8(N_("Mark off")));
830                 break;
831
832         case LFUN_MARK_ON:
833                 cur.clearSelection();
834                 cur.mark() = true;
835                 cur.resetAnchor();
836                 cur.message(from_utf8(N_("Mark on")));
837                 break;
838
839         case LFUN_MARK_TOGGLE:
840                 cur.clearSelection();
841                 if (cur.mark()) {
842                         cur.mark() = false;
843                         cur.message(from_utf8(N_("Mark removed")));
844                 } else {
845                         cur.mark() = true;
846                         cur.message(from_utf8(N_("Mark set")));
847                 }
848                 cur.resetAnchor();
849                 break;
850
851         case LFUN_SCREEN_RECENTER:
852                 center();
853                 break;
854
855         case LFUN_BIBTEX_DATABASE_ADD: {
856                 LCursor tmpcur = cursor_;
857                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
858                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
859                                                 InsetBase::BIBTEX_CODE);
860                 if (inset) {
861                         if (inset->addDatabase(to_utf8(cmd.argument())))
862                                 buffer_->updateBibfilesCache();
863                 }
864                 break;
865         }
866
867         case LFUN_BIBTEX_DATABASE_DEL: {
868                 LCursor tmpcur = cursor_;
869                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
870                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
871                                                 InsetBase::BIBTEX_CODE);
872                 if (inset) {
873                         if (inset->delDatabase(to_utf8(cmd.argument())))
874                                 buffer_->updateBibfilesCache();
875                 }
876                 break;
877         }
878
879         case LFUN_WORDS_COUNT: {
880                 DocIterator from, to;
881                 if (cur.selection()) {
882                         from = cur.selectionBegin();
883                         to = cur.selectionEnd();
884                 } else {
885                         from = doc_iterator_begin(buffer_->inset());
886                         to = doc_iterator_end(buffer_->inset());
887                 }
888                 int const count = countWords(from, to);
889                 docstring message;
890                 if (count != 1) {
891                         if (cur.selection())
892                                 message = bformat(_("%1$d words in selection."),
893                                           count);
894                                 else
895                                         message = bformat(_("%1$d words in document."),
896                                                           count);
897                 }
898                 else {
899                         if (cur.selection())
900                                 message = _("One word in selection.");
901                         else
902                                 message = _("One word in document.");
903                 }
904
905                 Alert::information(_("Count words"), message);
906         }
907                 break;
908
909         case LFUN_BUFFER_TOGGLE_COMPRESSION:
910                 // turn compression on/off
911                 buffer_->params().compressed = !buffer_->params().compressed;
912                 break;
913
914         case LFUN_NEXT_INSET_TOGGLE: {
915                 // this is the real function we want to invoke
916                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
917                 // if there is an inset at cursor, see whether it
918                 // wants to toggle.
919                 InsetBase * inset = cur.nextInset();
920                 if (inset && inset->isActive()) {
921                         LCursor tmpcur = cur;
922                         tmpcur.pushLeft(*inset);
923                         inset->dispatch(tmpcur, tmpcmd);
924                         if (tmpcur.result().dispatched()) {
925                                 cur.dispatched();
926                         }
927                 }
928                 // if it did not work, try the underlying inset.
929                 if (!cur.result().dispatched())
930                         cur.dispatch(tmpcmd);
931
932                 if (cur.result().dispatched())
933                         cur.clearSelection();
934
935                 break;
936         }
937
938         default:
939                 return false;
940         }
941
942         return true;
943 }
944
945
946 docstring const BufferView::requestSelection()
947 {
948         if (!buffer_)
949                 return docstring();
950
951         LCursor & cur = cursor_;
952
953         if (!cur.selection()) {
954                 xsel_cache_.set = false;
955                 return docstring();
956         }
957
958         if (!xsel_cache_.set ||
959             cur.top() != xsel_cache_.cursor ||
960             cur.anchor_.top() != xsel_cache_.anchor)
961         {
962                 xsel_cache_.cursor = cur.top();
963                 xsel_cache_.anchor = cur.anchor_.top();
964                 xsel_cache_.set = cur.selection();
965                 return cur.selectionAsString(false);
966         }
967         return docstring();
968 }
969
970
971 void BufferView::clearSelection()
972 {
973         if (buffer_) {
974                 cursor_.clearSelection();
975                 xsel_cache_.set = false;
976         }
977 }
978
979
980 void BufferView::workAreaResize(int width, int height)
981 {
982         bool const widthChange = width != width_;
983         bool const heightChange = height != height_;
984
985         // Update from work area
986         width_ = width;
987         height_ = height;
988
989         if (buffer_)
990                 resize();
991
992         update();
993 }
994
995
996 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
997 {
998         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
999
1000         // This is only called for mouse related events including
1001         // LFUN_FILE_OPEN generated by drag-and-drop.
1002         FuncRequest cmd = cmd0;
1003
1004         if (!buffer_)
1005                 return false;
1006
1007         LCursor cur(*this);
1008         cur.push(buffer_->inset());
1009         cur.selection() = cursor_.selection();
1010
1011         // Doesn't go through lyxfunc, so we need to update
1012         // the layout choice etc. ourselves
1013
1014         // E.g. Qt mouse press when no buffer
1015         if (!buffer_)
1016                 return false;
1017
1018         // Either the inset under the cursor or the
1019         // surrounding LyXText will handle this event.
1020
1021         // Build temporary cursor.
1022         cmd.y = min(max(cmd.y, -1), height_);
1023         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1024         //lyxerr << BOOST_CURRENT_FUNCTION
1025         //       << " * hit inset at tip: " << inset << endl;
1026         //lyxerr << BOOST_CURRENT_FUNCTION
1027         //       << " * created temp cursor:" << cur << endl;
1028
1029         // Put anchor at the same position.
1030         cur.resetAnchor();
1031
1032         // Try to dispatch to an non-editable inset near this position
1033         // via the temp cursor. If the inset wishes to change the real
1034         // cursor it has to do so explicitly by using
1035         //  cur.bv().cursor() = cur;  (or similar)
1036         if (inset)
1037                 inset->dispatch(cur, cmd);
1038
1039         // Now dispatch to the temporary cursor. If the real cursor should
1040         // be modified, the inset's dispatch has to do so explicitly.
1041         if (!cur.result().dispatched())
1042                 cur.dispatch(cmd);
1043
1044         if (cur.result().dispatched()) {
1045                 // Redraw if requested or necessary.
1046                 if (cur.result().update())
1047                         update(Update::FitCursor | Update::Force);
1048                 else
1049                         update(Update::FitCursor | Update::MultiParSel);
1050         }
1051
1052         return true;
1053 }
1054
1055
1056 void BufferView::scroll(int /*lines*/)
1057 {
1058 //      if (!buffer_)
1059 //              return;
1060 //
1061 //      LyXText const * t = &buffer_->text();
1062 //      int const line_height = defaultRowHeight();
1063 //
1064 //      // The new absolute coordinate
1065 //      int new_top_y = top_y() + lines * line_height;
1066 //
1067 //      // Restrict to a valid value
1068 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1069 //      new_top_y = std::max(0, new_top_y);
1070 //
1071 //      scrollDocView(new_top_y);
1072 //
1073 //      // Update the scrollbar.
1074 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1075 }
1076
1077
1078 void BufferView::setCursorFromRow(int row)
1079 {
1080         int tmpid = -1;
1081         int tmppos = -1;
1082
1083         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1084
1085         if (tmpid == -1)
1086                 buffer_->text().setCursor(cursor_, 0, 0);
1087         else
1088                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1089 }
1090
1091
1092 void BufferView::gotoLabel(docstring const & label)
1093 {
1094         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1095                 vector<docstring> labels;
1096                 it->getLabelList(*buffer_, labels);
1097                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1098                         setCursor(it);
1099                         update();
1100                         return;
1101                 }
1102         }
1103 }
1104
1105
1106 LyXText * BufferView::getLyXText()
1107 {
1108         LyXText * text = cursor_.innerText();
1109         BOOST_ASSERT(text);
1110         return text;
1111 }
1112
1113
1114 LyXText const * BufferView::getLyXText() const
1115 {
1116         LyXText const * text = cursor_.innerText();
1117         BOOST_ASSERT(text);
1118         return text;
1119 }
1120
1121
1122 int BufferView::workHeight() const
1123 {
1124         return height_;
1125 }
1126
1127
1128 void BufferView::setCursor(DocIterator const & dit)
1129 {
1130         size_t const n = dit.depth();
1131         for (size_t i = 0; i < n; ++i)
1132                 dit[i].inset().edit(cursor_, true);
1133
1134         cursor_.setCursor(dit);
1135         cursor_.selection() = false;
1136 }
1137
1138
1139 void BufferView::mouseSetCursor(LCursor & cur)
1140 {
1141         BOOST_ASSERT(&cur.bv() == this);
1142
1143         // Has the cursor just left the inset?
1144         bool badcursor = false;
1145         if (&cursor_.inset() != &cur.inset())
1146                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1147
1148         // do the dEPM magic if needed
1149         // FIXME: move this to InsetText::notifyCursorLeaves?
1150         if (!badcursor && cursor_.inTexted())
1151                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1152
1153         cursor_ = cur;
1154         cursor_.clearSelection();
1155         cursor_.setTargetX();
1156         finishUndo();
1157
1158 }
1159
1160
1161 void BufferView::putSelectionAt(DocIterator const & cur,
1162                                 int length, bool backwards)
1163 {
1164         cursor_.clearSelection();
1165
1166         setCursor(cur);
1167
1168         if (length) {
1169                 if (backwards) {
1170                         cursor_.pos() += length;
1171                         cursor_.setSelection(cursor_, -length);
1172                 } else
1173                         cursor_.setSelection(cursor_, length);
1174         }
1175 }
1176
1177
1178 LCursor & BufferView::cursor()
1179 {
1180         return cursor_;
1181 }
1182
1183
1184 LCursor const & BufferView::cursor() const
1185 {
1186         return cursor_;
1187 }
1188
1189
1190 pit_type BufferView::anchor_ref() const
1191 {
1192         return anchor_ref_;
1193 }
1194
1195
1196 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1197 {
1198         return metrics_info_;
1199 }
1200
1201
1202 void BufferView::updateMetrics(bool singlepar)
1203 {
1204         // FIXME (Abdel 19/10/2006):
1205         // There's something fishy in tabular. The coord_cache_ is not
1206         // correctly reconstructed when a character is trying to be inserted.
1207         // Not clearing out the coord_cache_ fixes the crash but there is a
1208         // bad side effect: buffer-begin and buffer-end do not update the screen.
1209         //
1210         // Remove old position cache
1211         coord_cache_.clear();
1212
1213         LyXText & buftext = buffer_->text();
1214         pit_type size = int(buftext.paragraphs().size());
1215
1216         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1217                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1218                 offset_ref_ = 0;
1219         }
1220
1221         pit_type const pit = anchor_ref_;
1222         int pit1 = pit;
1223         int pit2 = pit;
1224         size_t const npit = buftext.paragraphs().size();
1225
1226         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1227         // the (main text, not inset!) paragraph containing the cursor.
1228         // (if this paragraph contains insets etc., rebreaking will
1229         // recursively descend)
1230         if (!singlepar || pit == cursor_.bottom().pit())
1231                 buftext.redoParagraph(*this, pit);
1232         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1233
1234         // Redo paragraphs above anchor if necessary; again, in Single Par
1235         // mode, only if we encounter the (main text) one having the cursor.
1236         int y1 = y0;
1237         while (y1 > 0 && pit1 > 0) {
1238                 y1 -= buftext.getPar(pit1).ascent();
1239                 --pit1;
1240                 if (!singlepar || pit1 == cursor_.bottom().pit())
1241                         buftext.redoParagraph(*this, pit1);
1242                 y1 -= buftext.getPar(pit1).descent();
1243         }
1244
1245
1246         // Take care of ascent of first line
1247         y1 -= buftext.getPar(pit1).ascent();
1248
1249         // Normalize anchor for next time
1250         anchor_ref_ = pit1;
1251         offset_ref_ = -y1;
1252
1253         // Grey at the beginning is ugly
1254         if (pit1 == 0 && y1 > 0) {
1255                 y0 -= y1;
1256                 y1 = 0;
1257                 anchor_ref_ = 0;
1258         }
1259
1260         // Redo paragraphs below the anchor if necessary. Single par mode:
1261         // only the one containing the cursor if encountered.
1262         int y2 = y0;
1263         while (y2 < height_ && pit2 < int(npit) - 1) {
1264                 y2 += buftext.getPar(pit2).descent();
1265                 ++pit2;
1266                 if (!singlepar || pit2 == cursor_.bottom().pit())
1267                         buftext.redoParagraph(*this, pit2);
1268                 y2 += buftext.getPar(pit2).ascent();
1269         }
1270
1271         // Take care of descent of last line
1272         y2 += buftext.getPar(pit2).descent();
1273
1274         // The coordinates of all these paragraphs are correct, cache them
1275         int y = y1;
1276         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1277         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1278                 Paragraph const & par = buftext.getPar(pit);
1279                 y += par.ascent();
1280                 parPos[pit] = Point(0, y);
1281                 if (singlepar && pit == cursor_.bottom().pit()) {
1282                         // In Single Paragraph mode, collect here the
1283                         // y1 and y2 of the (one) paragraph the cursor is in
1284                         y1 = y - par.ascent();
1285                         y2 = y + par.descent();
1286                 }
1287                 y += par.descent();
1288         }
1289
1290         if (singlepar) {
1291                 // collect cursor paragraph iter bounds
1292                 pit1 = cursor_.bottom().pit();
1293                 pit2 = cursor_.bottom().pit();
1294         }
1295
1296         lyxerr[Debug::DEBUG]
1297                 << BOOST_CURRENT_FUNCTION
1298                 << " y1: " << y1
1299                 << " y2: " << y2
1300                 << " pit1: " << pit1
1301                 << " pit2: " << pit2
1302                 << " npit: " << npit
1303                 << " singlepar: " << singlepar
1304                 << "size: " << size
1305                 << endl;
1306
1307         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1308
1309         if (lyxerr.debugging(Debug::WORKAREA)) {
1310                 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1311                 coord_cache_.dump();
1312         }
1313 }
1314
1315
1316 void BufferView::menuInsertLyXFile(string const & filenm)
1317 {
1318         BOOST_ASSERT(cursor_.inTexted());
1319         string filename = filenm;
1320
1321         if (filename.empty()) {
1322                 // Launch a file browser
1323                 // FIXME UNICODE
1324                 string initpath = lyxrc.document_path;
1325
1326                 if (buffer_) {
1327                         string const trypath = buffer_->filePath();
1328                         // If directory is writeable, use this as default.
1329                         if (isDirWriteable(trypath))
1330                                 initpath = trypath;
1331                 }
1332
1333                 // FIXME UNICODE
1334                 FileDialog fileDlg(_("Select LyX document to insert"),
1335                         LFUN_FILE_INSERT,
1336                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1337                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1338
1339                 FileDialog::Result result =
1340                         fileDlg.open(from_utf8(initpath),
1341                                      FileFilterList(_("LyX Documents (*.lyx)")),
1342                                      docstring());
1343
1344                 if (result.first == FileDialog::Later)
1345                         return;
1346
1347                 // FIXME UNICODE
1348                 filename = to_utf8(result.second);
1349
1350                 // check selected filename
1351                 if (filename.empty()) {
1352                         // emit message signal.
1353                         message(_("Canceled."));
1354                         return;
1355                 }
1356         }
1357
1358         // Get absolute path of file and add ".lyx"
1359         // to the filename if necessary
1360         filename = fileSearch(string(), filename, "lyx");
1361
1362         docstring const disp_fn = makeDisplayPath(filename);
1363         // emit message signal.
1364         message(bformat(_("Inserting document %1$s..."), disp_fn));
1365
1366         docstring res;
1367         Buffer buf("", false);
1368         if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1369                 ErrorList & el = buffer_->errorList("Parse");
1370                 // Copy the inserted document error list into the current buffer one.
1371                 el = buf.errorList("Parse");
1372                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1373                                              buf.params().textclass, el);
1374                 res = _("Document %1$s inserted.");
1375         } else
1376                 res = _("Could not insert document %1$s");
1377
1378         // emit message signal.
1379         message(bformat(res, disp_fn));
1380         buffer_->errors("Parse");
1381         resize();
1382 }
1383
1384
1385 } // namespace lyx