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"
19 #include "dociterator.h"
21 #include "errorlist.h"
23 #include "FloatList.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
35 #include "TocBackend.h"
36 #include "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
41 #include "insets/insetinclude.h"
43 #include "support/filetools.h"
44 #include "support/fs_extras.h"
45 #include "support/lyxlib.h"
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
55 using support::bformat;
56 using support::FileName;
57 using support::libFileSearch;
58 using support::makeAbsPath;
59 using support::makeDisplayPath;
60 using support::onlyFilename;
61 using support::onlyPath;
62 using support::unlink;
67 namespace Alert = frontend::Alert;
68 namespace fs = boost::filesystem;
72 bool readFile(Buffer * const b, string const & s)
76 // File information about normal file
78 docstring const file = makeDisplayPath(s, 50);
79 docstring text = bformat(_("The specified document\n%1$s"
80 "\ncould not be read."), file);
81 Alert::error(_("Could not read document"), text);
85 // Check if emergency save file exists and is newer.
86 string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
88 if (fs::exists(e) && fs::exists(s)
89 && fs::last_write_time(e) > fs::last_write_time(s))
91 docstring const file = makeDisplayPath(s, 20);
92 docstring const text =
93 bformat(_("An emergency save of the document "
95 "Recover emergency save?"), file);
96 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
97 _("&Recover"), _("&Load Original"),
101 // the file is not saved if we load the emergency file.
103 return b->readFile(e);
111 // Now check if autosave file is newer.
112 string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
114 if (fs::exists(a) && fs::exists(s)
115 && fs::last_write_time(a) > fs::last_write_time(s))
117 docstring const file = makeDisplayPath(s, 20);
118 docstring const text =
119 bformat(_("The backup of the document "
120 "%1$s is newer.\n\nLoad the "
121 "backup instead?"), file);
122 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
123 _("&Load backup"), _("Load &original"),
127 // the file is not saved if we load the autosave file.
129 return b->readFile(a);
131 // Here we delete the autosave
132 unlink(FileName(makeAbsPath(a)));
138 return b->readFile(s);
146 bool loadLyXFile(Buffer * b, string const & s)
150 if (fs::is_readable(s)) {
151 if (readFile(b, s)) {
152 b->lyxvc().file_found_hook(s);
153 if (!fs::is_writable(s))
154 b->setReadonly(true);
158 docstring const file = makeDisplayPath(s, 20);
159 // Here we probably should run
160 if (LyXVC::file_not_found_hook(s)) {
161 docstring const text =
162 bformat(_("Do you want to retrieve the document"
163 " %1$s from version control?"), file);
164 int const ret = Alert::prompt(_("Retrieve from version control?"),
165 text, 0, 1, _("&Retrieve"), _("&Cancel"));
168 // How can we know _how_ to do the checkout?
169 // With the current VC support it has to be,
170 // a RCS file since CVS do not have special ,v files.
172 return loadLyXFile(b, s);
179 // FIXME newFile() should probably be a member method of Application...
180 Buffer * newFile(string const & filename, string const & templatename,
184 Buffer * b = theBufferList().newBuffer(filename);
188 // use defaults.lyx as a default template if it exists.
189 if (templatename.empty())
190 tname = libFileSearch("templates", "defaults.lyx").absFilename();
192 tname = templatename;
194 if (!tname.empty()) {
195 if (!b->readFile(tname)) {
196 docstring const file = makeDisplayPath(tname, 50);
197 docstring const text = bformat(
198 _("The specified document template\n%1$s\ncould not be read."),
200 Alert::error(_("Could not read template"), text);
201 theBufferList().release(b);
208 b->setFileName(filename);
211 b->setReadonly(false);
212 b->fully_loaded(true);
213 b->updateDocLang(b->params().language);
219 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
220 ErrorList & errorList)
222 TeXErrors::Errors::const_iterator cit = terr.begin();
223 TeXErrors::Errors::const_iterator end = terr.end();
225 for (; cit != end; ++cit) {
228 int errorrow = cit->error_in_line;
229 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
235 found = buf.texrow().getIdFromRow(errorrow, id_end,
237 } while (found && id_start == id_end && pos_start == pos_end);
239 errorList.push_back(ErrorItem(cit->error_desc,
240 cit->error_text, id_start, pos_start, pos_end));
245 string const bufferFormat(Buffer const & buffer)
247 if (buffer.isDocBook())
249 else if (buffer.isLiterate())
256 int countWords(DocIterator const & from, DocIterator const & to)
260 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
261 // Copied and adapted from isLetter() in ControlSpellChecker
263 && dit.pos() != dit.lastpos()
264 && dit.paragraph().isLetter(dit.pos())
265 && !dit.paragraph().isDeleted(dit.pos())) {
280 depth_type getDepth(DocIterator const & it)
282 depth_type depth = 0;
283 for (size_t i = 0 ; i < it.depth() ; ++i)
284 if (!it[i].inset().inMathed())
285 depth += it[i].paragraph().getDepth() + 1;
286 // remove 1 since the outer inset does not count
290 depth_type getItemDepth(ParIterator const & it)
292 Paragraph const & par = *it;
293 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
295 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
298 // this will hold the lowest depth encountered up to now.
299 depth_type min_depth = getDepth(it);
300 ParIterator prev_it = it;
303 --prev_it.top().pit();
305 // start of nested inset: go to outer par
307 if (prev_it.empty()) {
308 // start of document: nothing to do
313 // We search for the first paragraph with same label
314 // that is not more deeply nested.
315 Paragraph & prev_par = *prev_it;
316 depth_type const prev_depth = getDepth(prev_it);
317 if (labeltype == prev_par.layout()->labeltype) {
318 if (prev_depth < min_depth) {
319 return prev_par.itemdepth + 1;
321 else if (prev_depth == min_depth) {
322 return prev_par.itemdepth;
325 min_depth = std::min(min_depth, prev_depth);
326 // small optimization: if we are at depth 0, we won't
327 // find anything else
328 if (prev_depth == 0) {
335 bool needEnumCounterReset(ParIterator const & it)
337 Paragraph const & par = *it;
338 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
339 depth_type const cur_depth = par.getDepth();
340 ParIterator prev_it = it;
341 while (prev_it.pit()) {
342 --prev_it.top().pit();
343 Paragraph const & prev_par = *prev_it;
344 if (prev_par.getDepth() <= cur_depth)
345 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
347 // start of nested inset: reset
352 // set the label of a paragraph. This includes the counters.
353 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
355 Paragraph & par = *it;
356 LyXLayout_ptr const & layout = par.layout();
357 Counters & counters = textclass.counters();
360 par.params().appendix(par.params().startOfAppendix());
362 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
363 if (!par.params().appendix() &&
364 par.params().startOfAppendix()) {
365 par.params().appendix(true);
366 textclass.counters().reset();
370 // Compute the item depth of the paragraph
371 par.itemdepth = getItemDepth(it);
373 // erase what was there before
374 par.params().labelString(docstring());
376 if (layout->margintype == MARGIN_MANUAL) {
377 if (par.params().labelWidthString().empty())
378 par.setLabelWidthString(buf.translateLabel(layout->labelstring()));
380 par.setLabelWidthString(docstring());
383 // is it a layout that has an automatic label?
384 if (layout->labeltype == LABEL_COUNTER) {
385 if (layout->toclevel <= buf.params().secnumdepth
386 && (layout->latextype != LATEX_ENVIRONMENT
387 || isFirstInSequence(it.pit(), it.plist()))) {
388 counters.step(layout->counter);
389 docstring label = expandLabel(buf, layout,
390 par.params().appendix());
391 par.params().labelString(label);
393 } else if (layout->labeltype == LABEL_ITEMIZE) {
394 // At some point of time we should do something more
395 // clever here, like:
396 // par.params().labelString(
397 // buf.params().user_defined_bullet(par.itemdepth).getText());
398 // for now, use a simple hardcoded label
400 switch (par.itemdepth) {
402 itemlabel = char_type(0x2022);
405 itemlabel = char_type(0x2013);
408 itemlabel = char_type(0x2217);
411 itemlabel += char_type(0x2219); // or 0x00b7
415 par.params().labelString(itemlabel);
416 } else if (layout->labeltype == LABEL_ENUMERATE) {
418 // Yes I know this is a really, really! bad solution
420 docstring enumcounter = from_ascii("enum");
422 switch (par.itemdepth) {
434 // not a valid enumdepth...
438 // Maybe we have to reset the enumeration counter.
439 if (needEnumCounterReset(it))
440 counters.reset(enumcounter);
442 counters.step(enumcounter);
446 switch (par.itemdepth) {
448 format = N_("\\arabic{enumi}.");
451 format = N_("(\\alph{enumii})");
454 format = N_("\\roman{enumiii}.");
457 format = N_("\\Alph{enumiv}.");
460 // not a valid enumdepth...
464 par.params().labelString(counters.counterLabel(buf.B_(format)));
465 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
466 counters.step(from_ascii("bibitem"));
467 int number = counters.value(from_ascii("bibitem"));
469 par.bibitem()->setCounter(number);
470 par.params().labelString(buf.translateLabel(layout->labelstring()));
471 // In biblio should't be following counters but...
472 } else if (layout->labeltype == LABEL_SENSITIVE) {
473 // Search for the first float or wrap inset in the iterator
475 size_t i = it.depth();
478 InsetBase * const in = &it[i].inset();
479 if (in->lyxCode() == InsetBase::FLOAT_CODE
480 || in->lyxCode() == InsetBase::WRAP_CODE) {
481 type = in->getInsetName();
488 Floating const & fl = textclass.floats().getType(to_ascii(type));
490 counters.step(from_ascii(fl.type()));
492 // Doesn't work... yet.
493 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
495 // par->SetLayout(0);
496 s = buf.translateLabel(layout->labelstring());
499 par.params().labelString(s);
500 } else if (layout->labeltype == LABEL_NO_LABEL)
501 par.params().labelString(docstring());
503 par.params().labelString(buf.translateLabel(layout->labelstring()));
509 bool updateCurrentLabel(Buffer const & buf,
512 if (it == par_iterator_end(buf.inset()))
515 // if (it.lastpit == 0 && LyXText::isMainText(buf))
518 switch (it->layout()->labeltype) {
523 case LABEL_TOP_ENVIRONMENT:
524 case LABEL_CENTERED_TOP_ENVIRONMENT:
527 setLabel(buf, it, buf.params().getLyXTextClass());
530 case LABEL_SENSITIVE:
532 // do more things with enumerate later
533 case LABEL_ENUMERATE:
537 // This is dead code which get rid of a warning:
542 void updateLabels(Buffer const & buf,
543 ParIterator & from, ParIterator & to, bool childonly)
545 for (ParIterator it = from; it != to; ++it) {
546 if (it.pit() > it.lastpit())
548 if (!updateCurrentLabel (buf, it)) {
549 updateLabels(buf, childonly);
556 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
558 if (updateCurrentLabel(buf, iter))
561 updateLabels(buf, childonly);
565 void updateLabels(Buffer const & buf, bool childonly)
567 // Use the master text class also for child documents
568 LyXTextClass const & textclass = buf.params().getLyXTextClass();
571 // If this is a child document start with the master
572 Buffer const * const master = buf.getMasterBuffer();
573 if (master != &buf) {
574 updateLabels(*master);
578 // start over the counters
579 textclass.counters().reset();
582 ParIterator const end = par_iterator_end(buf.inset());
584 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
585 // reduce depth if necessary
587 Paragraph const & prevpar = it.plist()[it.pit() - 1];
588 it->params().depth(min(it->params().depth(),
589 prevpar.getMaxDepthAfter()));
591 it->params().depth(0);
593 // set the counter for this paragraph
594 setLabel(buf, it, textclass);
597 InsetList::const_iterator iit = it->insetlist.begin();
598 InsetList::const_iterator end = it->insetlist.end();
599 for (; iit != end; ++iit) {
600 if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
601 static_cast<InsetInclude const *>(iit->inset)
606 const_cast<Buffer &>(buf).tocBackend().update();
610 docstring expandLabel(Buffer const & buf,
611 LyXLayout_ptr const & layout, bool appendix)
613 LyXTextClass const & tclass = buf.params().getLyXTextClass();
615 docstring fmt = buf.translateLabel(appendix ?
616 layout->labelstring_appendix() :
617 layout->labelstring());
619 // handle 'inherited level parts' in 'fmt',
620 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
621 size_t const i = fmt.find('@', 0);
622 if (i != docstring::npos) {
623 size_t const j = fmt.find('@', i + 1);
624 if (j != docstring::npos) {
625 docstring parent(fmt, i + 1, j - i - 1);
627 docstring label = expandLabel(buf, tclass[to_utf8(parent)], appendix);
628 fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
632 return tclass.counters().counterLabel(fmt);