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"
42 #include "support/filetools.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
46 #include <boost/bind.hpp>
47 #include <boost/filesystem/operations.hpp>
54 using support::bformat;
55 using support::libFileSearch;
56 using support::makeDisplayPath;
57 using support::onlyFilename;
58 using support::onlyPath;
59 using support::unlink;
64 namespace Alert = frontend::Alert;
65 namespace fs = boost::filesystem;
69 bool readFile(Buffer * const b, string const & s)
73 // File information about normal file
75 docstring const file = makeDisplayPath(s, 50);
76 docstring text = bformat(_("The specified document\n%1$s"
77 "\ncould not be read."), file);
78 Alert::error(_("Could not read document"), text);
82 // Check if emergency save file exists and is newer.
83 string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
85 if (fs::exists(e) && fs::exists(s)
86 && fs::last_write_time(e) > fs::last_write_time(s))
88 docstring const file = makeDisplayPath(s, 20);
89 docstring const text =
90 bformat(_("An emergency save of the document "
92 "Recover emergency save?"), file);
93 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
94 _("&Recover"), _("&Load Original"),
98 // the file is not saved if we load the emergency file.
100 return b->readFile(e);
108 // Now check if autosave file is newer.
109 string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
111 if (fs::exists(a) && fs::exists(s)
112 && fs::last_write_time(a) > fs::last_write_time(s))
114 docstring const file = makeDisplayPath(s, 20);
115 docstring const text =
116 bformat(_("The backup of the document "
117 "%1$s is newer.\n\nLoad the "
118 "backup instead?"), file);
119 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
120 _("&Load backup"), _("Load &original"),
124 // the file is not saved if we load the autosave file.
126 return b->readFile(a);
128 // Here we delete the autosave
135 return b->readFile(s);
143 bool loadLyXFile(Buffer * b, string const & s)
147 if (fs::is_readable(s)) {
148 if (readFile(b, s)) {
149 b->lyxvc().file_found_hook(s);
150 if (!fs::is_writable(s))
151 b->setReadonly(true);
155 docstring const file = makeDisplayPath(s, 20);
156 // Here we probably should run
157 if (LyXVC::file_not_found_hook(s)) {
158 docstring const text =
159 bformat(_("Do you want to retrieve the document"
160 " %1$s from version control?"), file);
161 int const ret = Alert::prompt(_("Retrieve from version control?"),
162 text, 0, 1, _("&Retrieve"), _("&Cancel"));
165 // How can we know _how_ to do the checkout?
166 // With the current VC support it has to be,
167 // a RCS file since CVS do not have special ,v files.
169 return loadLyXFile(b, s);
176 // FIXME newFile() should probably be a member method of Application...
177 Buffer * newFile(string const & filename, string const & templatename,
181 Buffer * b = theBufferList().newBuffer(filename);
185 // use defaults.lyx as a default template if it exists.
186 if (templatename.empty())
187 tname = libFileSearch("templates", "defaults.lyx");
189 tname = templatename;
191 if (!tname.empty()) {
192 if (!b->readFile(tname)) {
193 docstring const file = makeDisplayPath(tname, 50);
194 docstring const text = bformat(
195 _("The specified document template\n%1$s\ncould not be read."),
197 Alert::error(_("Could not read template"), text);
198 theBufferList().release(b);
205 b->setFileName(filename);
208 b->setReadonly(false);
209 b->fully_loaded(true);
210 b->updateDocLang(b->params().language);
216 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
217 ErrorList & errorList)
219 TeXErrors::Errors::const_iterator cit = terr.begin();
220 TeXErrors::Errors::const_iterator end = terr.end();
222 for (; cit != end; ++cit) {
225 int errorrow = cit->error_in_line;
226 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
232 found = buf.texrow().getIdFromRow(errorrow, id_end,
234 } while (found && id_start == id_end && pos_start == pos_end);
236 errorList.push_back(ErrorItem(cit->error_desc,
237 cit->error_text, id_start, pos_start, pos_end));
242 string const bufferFormat(Buffer const & buffer)
244 if (buffer.isDocBook())
246 else if (buffer.isLiterate())
253 int countWords(DocIterator const & from, DocIterator const & to)
257 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
258 // Copied and adapted from isLetter() in ControlSpellChecker
260 && dit.pos() != dit.lastpos()
261 && dit.paragraph().isLetter(dit.pos())
262 && !dit.paragraph().isDeleted(dit.pos())) {
277 depth_type getDepth(DocIterator const & it)
279 depth_type depth = 0;
280 for (size_t i = 0 ; i < it.depth() ; ++i)
281 if (!it[i].inset().inMathed())
282 depth += it[i].paragraph().getDepth() + 1;
283 // remove 1 since the outer inset does not count
287 depth_type getItemDepth(ParIterator const & it)
289 Paragraph const & par = *it;
290 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
292 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
295 // this will hold the lowest depth encountered up to now.
296 depth_type min_depth = getDepth(it);
297 ParIterator prev_it = it;
300 --prev_it.top().pit();
302 // start of nested inset: go to outer par
304 if (prev_it.empty()) {
305 // start of document: nothing to do
310 // We search for the first paragraph with same label
311 // that is not more deeply nested.
312 Paragraph & prev_par = *prev_it;
313 depth_type const prev_depth = getDepth(prev_it);
314 if (labeltype == prev_par.layout()->labeltype) {
315 if (prev_depth < min_depth) {
316 return prev_par.itemdepth + 1;
318 else if (prev_depth == min_depth) {
319 return prev_par.itemdepth;
322 min_depth = std::min(min_depth, prev_depth);
323 // small optimization: if we are at depth 0, we won't
324 // find anything else
325 if (prev_depth == 0) {
332 bool needEnumCounterReset(ParIterator const & it)
334 Paragraph const & par = *it;
335 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
336 depth_type const cur_depth = par.getDepth();
337 ParIterator prev_it = it;
338 while (prev_it.pit()) {
339 --prev_it.top().pit();
340 Paragraph const & prev_par = *prev_it;
341 if (prev_par.getDepth() <= cur_depth)
342 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
344 // start of nested inset: reset
349 // set the label of a paragraph. This includes the counters.
350 void setLabel(Buffer const & buf, ParIterator & it)
352 Paragraph & par = *it;
353 BufferParams const & bufparams = buf.params();
354 LyXTextClass const & textclass = bufparams.getLyXTextClass();
355 LyXLayout_ptr const & layout = par.layout();
356 Counters & counters = textclass.counters();
359 par.params().appendix(par.params().startOfAppendix());
361 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
362 if (!par.params().appendix() &&
363 par.params().startOfAppendix()) {
364 par.params().appendix(true);
365 textclass.counters().reset();
369 // Compute the item depth of the paragraph
370 par.itemdepth = getItemDepth(it);
372 // erase what was there before
373 par.params().labelString(docstring());
375 if (layout->margintype == MARGIN_MANUAL) {
376 if (par.params().labelWidthString().empty())
377 par.setLabelWidthString(buf.translateLabel(layout->labelstring()));
379 par.setLabelWidthString(docstring());
382 // is it a layout that has an automatic label?
383 if (layout->labeltype == LABEL_COUNTER) {
384 if (layout->toclevel <= buf.params().secnumdepth
385 && (layout->latextype != LATEX_ENVIRONMENT
386 || isFirstInSequence(it.pit(), it.plist()))) {
387 counters.step(layout->counter);
388 docstring label = expandLabel(buf, layout,
389 par.params().appendix());
390 par.params().labelString(label);
392 } else if (layout->labeltype == LABEL_ITEMIZE) {
393 // At some point of time we should do something more
394 // clever here, like:
395 // par.params().labelString(
396 // bufparams.user_defined_bullet(par.itemdepth).getText());
397 // for now, use a simple hardcoded label
399 switch (par.itemdepth) {
401 itemlabel = char_type(0x2022);
404 itemlabel = char_type(0x2013);
407 itemlabel = char_type(0x2217);
410 itemlabel += char_type(0x2219); // or 0x00b7
414 par.params().labelString(itemlabel);
415 } else if (layout->labeltype == LABEL_ENUMERATE) {
417 // Yes I know this is a really, really! bad solution
419 docstring enumcounter = from_ascii("enum");
421 switch (par.itemdepth) {
433 // not a valid enumdepth...
437 // Maybe we have to reset the enumeration counter.
438 if (needEnumCounterReset(it))
439 counters.reset(enumcounter);
441 counters.step(enumcounter);
445 switch (par.itemdepth) {
447 format = N_("\\arabic{enumi}.");
450 format = N_("(\\alph{enumii})");
453 format = N_("\\roman{enumiii}.");
456 format = N_("\\Alph{enumiv}.");
459 // not a valid enumdepth...
463 par.params().labelString(counters.counterLabel(buf.B_(format)));
464 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
465 counters.step(from_ascii("bibitem"));
466 int number = counters.value(from_ascii("bibitem"));
468 par.bibitem()->setCounter(number);
469 par.params().labelString(buf.translateLabel(layout->labelstring()));
470 // In biblio should't be following counters but...
471 } else if (layout->labeltype == LABEL_SENSITIVE) {
472 // Search for the first float or wrap inset in the iterator
474 size_t i = it.depth();
477 InsetBase * const in = &it[i].inset();
478 if (in->lyxCode() == InsetBase::FLOAT_CODE
479 || in->lyxCode() == InsetBase::WRAP_CODE) {
480 type = in->getInsetName();
487 Floating const & fl = textclass.floats().getType(to_ascii(type));
489 counters.step(from_ascii(fl.type()));
491 // Doesn't work... yet.
492 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
494 // par->SetLayout(0);
495 s = buf.translateLabel(layout->labelstring());
498 par.params().labelString(s);
499 } else if (layout->labeltype == LABEL_NO_LABEL)
500 par.params().labelString(docstring());
502 par.params().labelString(buf.translateLabel(layout->labelstring()));
508 bool updateCurrentLabel(Buffer const & buf,
511 if (it == par_iterator_end(buf.inset()))
514 // if (it.lastpit == 0 && LyXText::isMainText(buf))
517 switch (it->layout()->labeltype) {
522 case LABEL_TOP_ENVIRONMENT:
523 case LABEL_CENTERED_TOP_ENVIRONMENT:
529 case LABEL_SENSITIVE:
531 // do more things with enumerate later
532 case LABEL_ENUMERATE:
536 // This is dead code which get rid of a warning:
541 void updateLabels(Buffer const & buf,
542 ParIterator & from, ParIterator & to)
544 for (ParIterator it = from; it != to; ++it) {
545 if (it.pit() > it.lastpit())
547 if (!updateCurrentLabel (buf, it)) {
555 void updateLabels(Buffer const & buf,
558 if (updateCurrentLabel(buf, iter))
565 void updateLabels(Buffer const & buf)
567 // start over the counters
568 buf.params().getLyXTextClass().counters().reset();
570 ParIterator const end = par_iterator_end(buf.inset());
572 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
573 // reduce depth if necessary
575 Paragraph const & prevpar = it.plist()[it.pit() - 1];
576 it->params().depth(min(it->params().depth(),
577 prevpar.getMaxDepthAfter()));
579 it->params().depth(0);
581 // set the counter for this paragraph
585 const_cast<Buffer &>(buf).tocBackend().update();
589 docstring expandLabel(Buffer const & buf,
590 LyXLayout_ptr const & layout, bool appendix)
592 LyXTextClass const & tclass = buf.params().getLyXTextClass();
594 docstring fmt = buf.translateLabel(appendix ?
595 layout->labelstring_appendix() :
596 layout->labelstring());
598 // handle 'inherited level parts' in 'fmt',
599 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
600 size_t const i = fmt.find('@', 0);
601 if (i != docstring::npos) {
602 size_t const j = fmt.find('@', i + 1);
603 if (j != docstring::npos) {
604 docstring parent(fmt, i + 1, j - i - 1);
606 docstring label = expandLabel(buf, tclass[to_utf8(parent)], appendix);
607 fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
611 return tclass.counters().counterLabel(fmt);