]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
9800c8d615ca59d2e5880e8038adbbd04c66fc0a
[lyx.git] / src / buffer_funcs.cpp
1 /**
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.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "debug.h"
20 #include "DocIterator.h"
21 #include "Counters.h"
22 #include "ErrorList.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "LaTeX.h"
30 #include "Layout.h"
31 #include "LyX.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"
40 #include "LyXVC.h"
41 #include "TexRow.h"
42 #include "Text.h"
43 #include "TocBackend.h"
44 #include "VCBackend.h"
45
46 #include "frontends/alert.h"
47
48 #include "insets/InsetBibitem.h"
49 #include "insets/InsetInclude.h"
50
51 #include "support/filetools.h"
52 #include "support/fs_extras.h"
53 #include "support/lyxlib.h"
54
55 #include <boost/bind.hpp>
56
57 using std::min;
58 using std::string;
59
60
61 namespace lyx {
62
63 using namespace std;
64
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;
73
74 namespace Alert = frontend::Alert;
75
76 namespace {
77
78 bool readFile(Buffer * const b, FileName const & s)
79 {
80         BOOST_ASSERT(b);
81
82         // File information about normal file
83         if (!s.exists()) {
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);
88                 return false;
89         }
90
91         // Check if emergency save file exists and is newer.
92         FileName const e(s.absFilename() + ".emergency");
93
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 "
98                                   "%1$s exists.\n\n"
99                                                "Recover emergency save?"), file);
100                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
101                                       _("&Recover"),  _("&Load Original"),
102                                       _("&Cancel")))
103                 {
104                 case 0:
105                         // the file is not saved if we load the emergency file.
106                         b->markDirty();
107                         return b->readFile(e);
108                 case 1:
109                         break;
110                 default:
111                         return false;
112                 }
113         }
114
115         // Now check if autosave file is newer.
116         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
117
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"),
126                                       _("&Cancel") ))
127                 {
128                 case 0:
129                         // the file is not saved if we load the autosave file.
130                         b->markDirty();
131                         return b->readFile(a);
132                 case 1:
133                         // Here we delete the autosave
134                         unlink(a);
135                         break;
136                 default:
137                         return false;
138                 }
139         }
140         return b->readFile(s);
141 }
142
143
144 } // namespace anon
145
146
147
148 bool loadLyXFile(Buffer * b, FileName const & s)
149 {
150         BOOST_ASSERT(b);
151
152         if (s.isReadable()) {
153                 if (readFile(b, s)) {
154                         b->lyxvc().file_found_hook(s);
155                         if (!s.isWritable())
156                                 b->setReadonly(true);
157                         return true;
158                 }
159         } else {
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"));
168
169                         if (ret == 0) {
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.
173                                 RCS::retrieve(s);
174                                 return loadLyXFile(b, s);
175                         }
176                 }
177         }
178         return false;
179 }
180
181
182 bool checkIfLoaded(FileName const & fn)
183 {
184         return theBufferList().getBuffer(fn.absFilename());
185 }
186
187
188 Buffer * checkAndLoadLyXFile(FileName const & filename)
189 {
190         // File already open?
191         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
192         if (checkBuffer) {
193                 if (checkBuffer->isClean())
194                         return checkBuffer;
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")))
201                         return checkBuffer;
202
203                 // FIXME: should be LFUN_REVERT
204                 if (theBufferList().close(checkBuffer, false))
205                         // Load it again.
206                         return checkAndLoadLyXFile(filename);
207                 else
208                         // The file could not be closed.
209                         return 0;
210         }
211
212         if (filename.isReadable()) {
213                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
214                 if (!lyx::loadLyXFile(b, filename)) {
215                         theBufferList().release(b);
216                         return 0;
217                 }
218                 return b;
219         }
220
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);
227
228         return 0;
229 }
230
231 // FIXME newFile() should probably be a member method of Application...
232 Buffer * newFile(string const & filename, string const & templatename,
233                  bool const isNamed)
234 {
235         // get a free buffer
236         Buffer * b = theBufferList().newBuffer(filename);
237         BOOST_ASSERT(b);
238
239         FileName tname;
240         // use defaults.lyx as a default template if it exists.
241         if (templatename.empty())
242                 tname = libFileSearch("templates", "defaults.lyx");
243         else
244                 tname = makeAbsPath(templatename);
245
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."),
251                                 file);
252                         Alert::error(_("Could not read template"), text);
253                         theBufferList().release(b);
254                         return 0;
255                 }
256         }
257
258         if (!isNamed) {
259                 b->setUnnamed();
260                 b->setFileName(filename);
261         }
262
263         b->setReadonly(false);
264         b->fully_loaded(true);
265
266         return b;
267 }
268
269
270 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
271                                   ErrorList & errorList)
272 {
273         TeXErrors::Errors::const_iterator cit = terr.begin();
274         TeXErrors::Errors::const_iterator end = terr.end();
275
276         for (; cit != end; ++cit) {
277                 int id_start = -1;
278                 int pos_start = -1;
279                 int errorrow = cit->error_in_line;
280                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
281                                                        pos_start);
282                 int id_end = -1;
283                 int pos_end = -1;
284                 do {
285                         ++errorrow;
286                         found = buf.texrow().getIdFromRow(errorrow, id_end,
287                                                           pos_end);
288                 } while (found && id_start == id_end && pos_start == pos_end);
289
290                 errorList.push_back(ErrorItem(cit->error_desc,
291                         cit->error_text, id_start, pos_start, pos_end));
292         }
293 }
294
295
296 string const bufferFormat(Buffer const & buffer)
297 {
298         if (buffer.isDocBook())
299                 return "docbook";
300         else if (buffer.isLiterate())
301                 return "literate";
302         else
303                 return "latex";
304 }
305
306
307 int countWords(DocIterator const & from, DocIterator const & to)
308 {
309         int count = 0;
310         bool inword = false;
311         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
312                 // Copied and adapted from isLetter() in ControlSpellChecker
313                 if (dit.inTexted()
314                     && dit.pos() != dit.lastpos()
315                     && dit.paragraph().isLetter(dit.pos())
316                     && !dit.paragraph().isDeleted(dit.pos())) {
317                         if (!inword) {
318                                 ++count;
319                                 inword = true;
320                         }
321                 } else if (inword)
322                         inword = false;
323         }
324
325         return count;
326 }
327
328
329 namespace {
330
331 depth_type getDepth(DocIterator const & it)
332 {
333         depth_type depth = 0;
334         for (size_t i = 0 ; i < it.depth() ; ++i)
335                 if (!it[i].inset().inMathed())
336                         depth += it[i].paragraph().getDepth() + 1;
337         // remove 1 since the outer inset does not count
338         return depth - 1;
339 }
340
341 depth_type getItemDepth(ParIterator const & it)
342 {
343         Paragraph const & par = *it;
344         LabelType const labeltype = par.layout()->labeltype;
345
346         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
347                 return 0;
348
349         // this will hold the lowest depth encountered up to now.
350         depth_type min_depth = getDepth(it);
351         ParIterator prev_it = it;
352         while (true) {
353                 if (prev_it.pit())
354                         --prev_it.top().pit();
355                 else {
356                         // start of nested inset: go to outer par
357                         prev_it.pop_back();
358                         if (prev_it.empty()) {
359                                 // start of document: nothing to do
360                                 return 0;
361                         }
362                 }
363
364                 // We search for the first paragraph with same label
365                 // that is not more deeply nested.
366                 Paragraph & prev_par = *prev_it;
367                 depth_type const prev_depth = getDepth(prev_it);
368                 if (labeltype == prev_par.layout()->labeltype) {
369                         if (prev_depth < min_depth) {
370                                 return prev_par.itemdepth + 1;
371                         }
372                         else if (prev_depth == min_depth) {
373                                 return prev_par.itemdepth;
374                         }
375                 }
376                 min_depth = std::min(min_depth, prev_depth);
377                 // small optimization: if we are at depth 0, we won't
378                 // find anything else
379                 if (prev_depth == 0) {
380                         return 0;
381                 }
382         }
383 }
384
385
386 bool needEnumCounterReset(ParIterator const & it)
387 {
388         Paragraph const & par = *it;
389         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
390         depth_type const cur_depth = par.getDepth();
391         ParIterator prev_it = it;
392         while (prev_it.pit()) {
393                 --prev_it.top().pit();
394                 Paragraph const & prev_par = *prev_it;
395                 if (prev_par.getDepth() <= cur_depth)
396                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
397         }
398         // start of nested inset: reset
399         return true;
400 }
401
402
403 // set the label of a paragraph. This includes the counters.
404 void setLabel(Buffer const & buf, ParIterator & it)
405 {
406         TextClass const & textclass = buf.params().getTextClass();
407         Paragraph & par = it.paragraph();
408         LayoutPtr const & layout = par.layout();
409         Counters & counters = textclass.counters();
410
411         if (par.params().startOfAppendix()) {
412                 // FIXME: only the counter corresponding to toplevel
413                 // sectionning should be reset
414                 counters.reset();
415                 counters.appendix(true);
416         }
417         par.params().appendix(counters.appendix());
418
419         // Compute the item depth of the paragraph
420         par.itemdepth = getItemDepth(it);
421
422         if (layout->margintype == MARGIN_MANUAL) {
423                 if (par.params().labelWidthString().empty())
424                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
425         } else {
426                 par.params().labelWidthString(docstring());
427         }
428
429         switch(layout->labeltype) {
430         case LABEL_COUNTER:
431                 if (layout->toclevel <= buf.params().secnumdepth
432                     && (layout->latextype != LATEX_ENVIRONMENT
433                         || isFirstInSequence(it.pit(), it.plist()))) {
434                         counters.step(layout->counter);
435                         par.params().labelString(
436                                 par.expandLabel(layout, buf.params()));
437                 } else
438                         par.params().labelString(docstring());
439                 break;
440
441         case LABEL_ITEMIZE: {
442                 // At some point of time we should do something more
443                 // clever here, like:
444                 //   par.params().labelString(
445                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
446                 // for now, use a simple hardcoded label
447                 docstring itemlabel;
448                 switch (par.itemdepth) {
449                 case 0:
450                         itemlabel = char_type(0x2022);
451                         break;
452                 case 1:
453                         itemlabel = char_type(0x2013);
454                         break;
455                 case 2:
456                         itemlabel = char_type(0x2217);
457                         break;
458                 case 3:
459                         itemlabel = char_type(0x2219); // or 0x00b7
460                         break;
461                 }
462                 par.params().labelString(itemlabel);
463                 break;
464         }
465
466         case LABEL_ENUMERATE: {
467                 // FIXME: Yes I know this is a really, really! bad solution
468                 // (Lgb)
469                 docstring enumcounter = from_ascii("enum");
470
471                 switch (par.itemdepth) {
472                 case 2:
473                         enumcounter += 'i';
474                 case 1:
475                         enumcounter += 'i';
476                 case 0:
477                         enumcounter += 'i';
478                         break;
479                 case 3:
480                         enumcounter += "iv";
481                         break;
482                 default:
483                         // not a valid enumdepth...
484                         break;
485                 }
486
487                 // Maybe we have to reset the enumeration counter.
488                 if (needEnumCounterReset(it))
489                         counters.reset(enumcounter);
490
491                 counters.step(enumcounter);
492
493                 string format;
494
495                 switch (par.itemdepth) {
496                 case 0:
497                         format = N_("\\arabic{enumi}.");
498                         break;
499                 case 1:
500                         format = N_("(\\alph{enumii})");
501                         break;
502                 case 2:
503                         format = N_("\\roman{enumiii}.");
504                         break;
505                 case 3:
506                         format = N_("\\Alph{enumiv}.");
507                         break;
508                 default:
509                         // not a valid enumdepth...
510                         break;
511                 }
512
513                 par.params().labelString(counters.counterLabel(
514                         par.translateIfPossible(from_ascii(format), buf.params())));
515
516                 break;
517         }
518
519         case LABEL_SENSITIVE: {
520                 string const & type = counters.current_float();
521                 docstring full_label;
522                 if (type.empty())
523                         full_label = buf.B_("Senseless!!! ");
524                 else {
525                         docstring name = buf.B_(textclass.floats().getType(type).name());
526                         if (counters.hasCounter(from_utf8(type))) {
527                                 counters.step(from_utf8(type));
528                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
529                                                      name, 
530                                                      counters.theCounter(from_utf8(type)));
531                         } else
532                                 full_label = bformat(from_ascii("%1$s #:"), name);      
533                 }
534                 par.params().labelString(full_label);   
535                 break;
536         }
537
538         case LABEL_NO_LABEL:
539                 par.params().labelString(docstring());
540                 break;
541
542         case LABEL_MANUAL:
543         case LABEL_TOP_ENVIRONMENT:
544         case LABEL_CENTERED_TOP_ENVIRONMENT:
545         case LABEL_STATIC:      
546         case LABEL_BIBLIO:
547                 par.params().labelString(
548                         par.translateIfPossible(layout->labelstring(), 
549                                                 buf.params()));
550                 break;
551         }
552 }
553
554 } // anon namespace
555
556 void updateLabels(Buffer const & buf, ParIterator & parit)
557 {
558         BOOST_ASSERT(parit.pit() == 0);
559
560         depth_type maxdepth = 0;
561         pit_type const lastpit = parit.lastpit();
562         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
563                 // reduce depth if necessary
564                 parit->params().depth(min(parit->params().depth(), maxdepth));
565                 maxdepth = parit->getMaxDepthAfter();
566
567                 // set the counter for this paragraph
568                 setLabel(buf, parit);
569
570                 // Now the insets
571                 InsetList::const_iterator iit = parit->insetList().begin();
572                 InsetList::const_iterator end = parit->insetList().end();
573                 for (; iit != end; ++iit) {
574                         parit.pos() = iit->pos;
575                         iit->inset->updateLabels(buf, parit);
576                 }
577         }
578         
579 }
580
581
582 // FIXME: buf should should be const because updateLabels() modifies
583 // the contents of the paragraphs.
584 void updateLabels(Buffer const & buf, bool childonly)
585 {
586         Buffer const * const master = buf.getMasterBuffer();
587         // Use the master text class also for child documents
588         TextClass const & textclass = master->params().getTextClass();
589
590         if (!childonly) {
591                 // If this is a child document start with the master
592                 if (master != &buf) {
593                         updateLabels(*master);
594                         return;
595                 }
596
597                 // start over the counters
598                 textclass.counters().reset();
599         }
600
601         Buffer & cbuf = const_cast<Buffer &>(buf);
602
603         if (buf.text().empty()) {
604                 // FIXME: we don't call continue with updateLabels()
605                 // here because it crashes on newly created documents.
606                 // But the TocBackend needs to be initialised
607                 // nonetheless so we update the tocBackend manually.
608                 cbuf.tocBackend().update();
609                 return;
610         }
611
612         // do the real work
613         ParIterator parit = par_iterator_begin(buf.inset());
614         updateLabels(buf, parit);
615
616         cbuf.tocBackend().update();
617         if (!childonly)
618                 cbuf.structureChanged();
619         // FIXME
620         // the embedding signal is emitted with structureChanged signal
621         // this is inaccurate so these two will be separated later.
622         //cbuf.embeddedFiles().update();
623         //cbuf.embeddingChanged();
624 }
625
626
627 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
628 {
629         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
630                 Buffer * master = buffer.getMasterBuffer();
631                 master->tocBackend().updateItem(par_it);
632                 master->structureChanged();
633         }
634 }
635
636 textclass_type defaultTextclass()
637 {
638         // We want to return the article class. if `first' is
639         // true in the returned pair, then `second' is the textclass
640         // number; if it is false, second is 0. In both cases, second
641         // is what we want.
642         return textclasslist.numberOfClass("article").second;
643 }
644
645
646 void loadChildDocuments(Buffer const & buf)
647 {
648         bool parse_error = false;
649                 
650         for (InsetIterator it = inset_iterator_begin(buf.inset()); it; ++it) {
651                 if (it->lyxCode() != INCLUDE_CODE)
652                         continue;
653                 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
654                 InsetCommandParams const & ip = inset.params();
655                 Buffer * child = loadIfNeeded(buf, ip);
656                 if (!child)
657                         continue;
658                 parse_error |= !child->errorList("Parse").empty();
659                 loadChildDocuments(*child);
660         }
661
662         if (use_gui && buf.getMasterBuffer() == &buf)
663                 updateLabels(buf);
664 }
665 } // namespace lyx