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