2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
20 #include "DocIterator.h"
22 #include "ErrorList.h"
24 #include "FloatList.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
32 #include "lyxlayout_ptr_fwd.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
43 #include "TocBackend.h"
44 #include "VCBackend.h"
46 #include "frontends/alert.h"
48 #include "insets/InsetBibitem.h"
49 #include "insets/InsetInclude.h"
51 #include "support/filetools.h"
52 #include "support/fs_extras.h"
53 #include "support/lyxlib.h"
55 #include <boost/bind.hpp>
65 using support::bformat;
66 using support::FileName;
67 using support::libFileSearch;
68 using support::makeAbsPath;
69 using support::makeDisplayPath;
70 using support::onlyFilename;
71 using support::onlyPath;
72 using support::unlink;
74 namespace Alert = frontend::Alert;
78 bool readFile(Buffer * const b, FileName const & s)
82 // File information about normal file
84 docstring const file = makeDisplayPath(s.absFilename(), 50);
85 docstring text = bformat(_("The specified document\n%1$s"
86 "\ncould not be read."), file);
87 Alert::error(_("Could not read document"), text);
91 // Check if emergency save file exists and is newer.
92 FileName const e(s.absFilename() + ".emergency");
94 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
95 docstring const file = makeDisplayPath(s.absFilename(), 20);
96 docstring const text =
97 bformat(_("An emergency save of the document "
99 "Recover emergency save?"), file);
100 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
101 _("&Recover"), _("&Load Original"),
105 // the file is not saved if we load the emergency file.
107 return b->readFile(e);
115 // Now check if autosave file is newer.
116 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
118 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
119 docstring const file = makeDisplayPath(s.absFilename(), 20);
120 docstring const text =
121 bformat(_("The backup of the document "
122 "%1$s is newer.\n\nLoad the "
123 "backup instead?"), file);
124 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
125 _("&Load backup"), _("Load &original"),
129 // the file is not saved if we load the autosave file.
131 return b->readFile(a);
133 // Here we delete the autosave
140 return b->readFile(s);
148 bool loadLyXFile(Buffer * b, FileName const & s)
152 if (s.isReadable()) {
153 if (readFile(b, s)) {
154 b->lyxvc().file_found_hook(s);
156 b->setReadonly(true);
160 docstring const file = makeDisplayPath(s.absFilename(), 20);
161 // Here we probably should run
162 if (LyXVC::file_not_found_hook(s)) {
163 docstring const text =
164 bformat(_("Do you want to retrieve the document"
165 " %1$s from version control?"), file);
166 int const ret = Alert::prompt(_("Retrieve from version control?"),
167 text, 0, 1, _("&Retrieve"), _("&Cancel"));
170 // How can we know _how_ to do the checkout?
171 // With the current VC support it has to be,
172 // a RCS file since CVS do not have special ,v files.
174 return loadLyXFile(b, s);
182 bool checkIfLoaded(FileName const & fn)
184 return theBufferList().getBuffer(fn.absFilename());
188 Buffer * checkAndLoadLyXFile(FileName const & filename)
190 // File already open?
191 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
193 if (checkBuffer->isClean())
195 docstring const file = makeDisplayPath(filename.absFilename(), 20);
196 docstring text = bformat(_(
197 "The document %1$s is already loaded and has unsaved changes.\n"
198 "Do you want to abandon your changes and reload the version on disk?"), file);
199 if (Alert::prompt(_("Reload saved document?"),
200 text, 0, 1, _("&Reload"), _("&Keep Changes")))
203 // FIXME: should be LFUN_REVERT
204 if (theBufferList().close(checkBuffer, false))
206 return checkAndLoadLyXFile(filename);
208 // The file could not be closed.
212 if (filename.isReadable()) {
213 Buffer * b = theBufferList().newBuffer(filename.absFilename());
214 if (!lyx::loadLyXFile(b, filename)) {
215 theBufferList().release(b);
221 docstring text = bformat(_("The document %1$s does not yet "
222 "exist.\n\nDo you want to create a new document?"),
223 from_utf8(filename.absFilename()));
224 if (!Alert::prompt(_("Create new document?"),
225 text, 0, 1, _("&Create"), _("Cancel")))
226 return newFile(filename.absFilename(), string(), true);
231 // FIXME newFile() should probably be a member method of Application...
232 Buffer * newFile(string const & filename, string const & templatename,
236 Buffer * b = theBufferList().newBuffer(filename);
240 // use defaults.lyx as a default template if it exists.
241 if (templatename.empty())
242 tname = libFileSearch("templates", "defaults.lyx");
244 tname = makeAbsPath(templatename);
246 if (!tname.empty()) {
247 if (!b->readFile(tname)) {
248 docstring const file = makeDisplayPath(tname.absFilename(), 50);
249 docstring const text = bformat(
250 _("The specified document template\n%1$s\ncould not be read."),
252 Alert::error(_("Could not read template"), text);
253 theBufferList().release(b);
260 b->setFileName(filename);
263 b->setReadonly(false);
264 b->setFullyLoaded(true);
270 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
271 ErrorList & errorList)
273 TeXErrors::Errors::const_iterator cit = terr.begin();
274 TeXErrors::Errors::const_iterator end = terr.end();
276 for (; cit != end; ++cit) {
279 int errorrow = cit->error_in_line;
280 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
286 found = buf.texrow().getIdFromRow(errorrow, id_end,
288 } while (found && id_start == id_end && pos_start == pos_end);
290 errorList.push_back(ErrorItem(cit->error_desc,
291 cit->error_text, id_start, pos_start, pos_end));
296 int countWords(DocIterator const & from, DocIterator const & to)
300 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
301 // Copied and adapted from isLetter() in ControlSpellChecker
303 && dit.pos() != dit.lastpos()
304 && dit.paragraph().isLetter(dit.pos())
305 && !dit.paragraph().isDeleted(dit.pos())) {
320 depth_type getDepth(DocIterator const & it)
322 depth_type depth = 0;
323 for (size_t i = 0 ; i < it.depth() ; ++i)
324 if (!it[i].inset().inMathed())
325 depth += it[i].paragraph().getDepth() + 1;
326 // remove 1 since the outer inset does not count
330 depth_type getItemDepth(ParIterator const & it)
332 Paragraph const & par = *it;
333 LabelType const labeltype = par.layout()->labeltype;
335 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
338 // this will hold the lowest depth encountered up to now.
339 depth_type min_depth = getDepth(it);
340 ParIterator prev_it = it;
343 --prev_it.top().pit();
345 // start of nested inset: go to outer par
347 if (prev_it.empty()) {
348 // start of document: nothing to do
353 // We search for the first paragraph with same label
354 // that is not more deeply nested.
355 Paragraph & prev_par = *prev_it;
356 depth_type const prev_depth = getDepth(prev_it);
357 if (labeltype == prev_par.layout()->labeltype) {
358 if (prev_depth < min_depth) {
359 return prev_par.itemdepth + 1;
361 else if (prev_depth == min_depth) {
362 return prev_par.itemdepth;
365 min_depth = std::min(min_depth, prev_depth);
366 // small optimization: if we are at depth 0, we won't
367 // find anything else
368 if (prev_depth == 0) {
375 bool needEnumCounterReset(ParIterator const & it)
377 Paragraph const & par = *it;
378 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
379 depth_type const cur_depth = par.getDepth();
380 ParIterator prev_it = it;
381 while (prev_it.pit()) {
382 --prev_it.top().pit();
383 Paragraph const & prev_par = *prev_it;
384 if (prev_par.getDepth() <= cur_depth)
385 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
387 // start of nested inset: reset
392 // set the label of a paragraph. This includes the counters.
393 void setLabel(Buffer const & buf, ParIterator & it)
395 TextClass const & textclass = buf.params().getTextClass();
396 Paragraph & par = it.paragraph();
397 LayoutPtr const & layout = par.layout();
398 Counters & counters = textclass.counters();
400 if (par.params().startOfAppendix()) {
401 // FIXME: only the counter corresponding to toplevel
402 // sectionning should be reset
404 counters.appendix(true);
406 par.params().appendix(counters.appendix());
408 // Compute the item depth of the paragraph
409 par.itemdepth = getItemDepth(it);
411 if (layout->margintype == MARGIN_MANUAL) {
412 if (par.params().labelWidthString().empty())
413 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
415 par.params().labelWidthString(docstring());
418 switch(layout->labeltype) {
420 if (layout->toclevel <= buf.params().secnumdepth
421 && (layout->latextype != LATEX_ENVIRONMENT
422 || isFirstInSequence(it.pit(), it.plist()))) {
423 counters.step(layout->counter);
424 par.params().labelString(
425 par.expandLabel(layout, buf.params()));
427 par.params().labelString(docstring());
430 case LABEL_ITEMIZE: {
431 // At some point of time we should do something more
432 // clever here, like:
433 // par.params().labelString(
434 // buf.params().user_defined_bullet(par.itemdepth).getText());
435 // for now, use a simple hardcoded label
437 switch (par.itemdepth) {
439 itemlabel = char_type(0x2022);
442 itemlabel = char_type(0x2013);
445 itemlabel = char_type(0x2217);
448 itemlabel = char_type(0x2219); // or 0x00b7
451 par.params().labelString(itemlabel);
455 case LABEL_ENUMERATE: {
456 // FIXME: Yes I know this is a really, really! bad solution
458 docstring enumcounter = from_ascii("enum");
460 switch (par.itemdepth) {
472 // not a valid enumdepth...
476 // Maybe we have to reset the enumeration counter.
477 if (needEnumCounterReset(it))
478 counters.reset(enumcounter);
480 counters.step(enumcounter);
484 switch (par.itemdepth) {
486 format = N_("\\arabic{enumi}.");
489 format = N_("(\\alph{enumii})");
492 format = N_("\\roman{enumiii}.");
495 format = N_("\\Alph{enumiv}.");
498 // not a valid enumdepth...
502 par.params().labelString(counters.counterLabel(
503 par.translateIfPossible(from_ascii(format), buf.params())));
508 case LABEL_SENSITIVE: {
509 string const & type = counters.current_float();
510 docstring full_label;
512 full_label = buf.B_("Senseless!!! ");
514 docstring name = buf.B_(textclass.floats().getType(type).name());
515 if (counters.hasCounter(from_utf8(type))) {
516 counters.step(from_utf8(type));
517 full_label = bformat(from_ascii("%1$s %2$s:"),
519 counters.theCounter(from_utf8(type)));
521 full_label = bformat(from_ascii("%1$s #:"), name);
523 par.params().labelString(full_label);
528 par.params().labelString(docstring());
532 case LABEL_TOP_ENVIRONMENT:
533 case LABEL_CENTERED_TOP_ENVIRONMENT:
536 par.params().labelString(
537 par.translateIfPossible(layout->labelstring(),
545 void updateLabels(Buffer const & buf, ParIterator & parit)
547 BOOST_ASSERT(parit.pit() == 0);
549 depth_type maxdepth = 0;
550 pit_type const lastpit = parit.lastpit();
551 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
552 // reduce depth if necessary
553 parit->params().depth(min(parit->params().depth(), maxdepth));
554 maxdepth = parit->getMaxDepthAfter();
556 // set the counter for this paragraph
557 setLabel(buf, parit);
560 InsetList::const_iterator iit = parit->insetList().begin();
561 InsetList::const_iterator end = parit->insetList().end();
562 for (; iit != end; ++iit) {
563 parit.pos() = iit->pos;
564 iit->inset->updateLabels(buf, parit);
571 // FIXME: buf should should be const because updateLabels() modifies
572 // the contents of the paragraphs.
573 void updateLabels(Buffer const & buf, bool childonly)
575 Buffer const * const master = buf.masterBuffer();
576 // Use the master text class also for child documents
577 TextClass const & textclass = master->params().getTextClass();
580 // If this is a child document start with the master
581 if (master != &buf) {
582 updateLabels(*master);
586 // start over the counters
587 textclass.counters().reset();
590 Buffer & cbuf = const_cast<Buffer &>(buf);
592 if (buf.text().empty()) {
593 // FIXME: we don't call continue with updateLabels()
594 // here because it crashes on newly created documents.
595 // But the TocBackend needs to be initialised
596 // nonetheless so we update the tocBackend manually.
597 cbuf.tocBackend().update();
602 ParIterator parit = par_iterator_begin(buf.inset());
603 updateLabels(buf, parit);
605 cbuf.tocBackend().update();
607 cbuf.structureChanged();
609 // the embedding signal is emitted with structureChanged signal
610 // this is inaccurate so these two will be separated later.
611 //cbuf.embeddedFiles().update();
612 //cbuf.embeddingChanged();
616 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
618 if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
619 Buffer * master = buffer.masterBuffer();
620 master->tocBackend().updateItem(par_it);
621 master->structureChanged();
626 textclass_type defaultTextclass()
628 // We want to return the article class. if `first' is
629 // true in the returned pair, then `second' is the textclass
630 // number; if it is false, second is 0. In both cases, second
632 return textclasslist.numberOfClass("article").second;