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