]> git.lyx.org Git - lyx.git/blob - src/buffer.C
2cc84449377e59820af902e1ba9c5f19b8e67cb9
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "Bullet.h"
20 #include "Chktex.h"
21 #include "debug.h"
22 #include "errorlist.h"
23 #include "exporter.h"
24 #include "format.h"
25 #include "funcrequest.h"
26 #include "gettext.h"
27 #include "iterators.h"
28 #include "language.h"
29 #include "LaTeX.h"
30 #include "LaTeXFeatures.h"
31 #include "LyXAction.h"
32 #include "lyxlex.h"
33 #include "lyxrc.h"
34 #include "lyxvc.h"
35 #include "messages.h"
36 #include "output.h"
37 #include "output_docbook.h"
38 #include "output_latex.h"
39 #include "output_linuxdoc.h"
40 #include "paragraph.h"
41 #include "paragraph_funcs.h"
42 #include "ParagraphParameters.h"
43 #include "PosIterator.h"
44 #include "sgml.h"
45 #include "texrow.h"
46 #include "undo.h"
47 #include "version.h"
48
49 #include "insets/insetbibitem.h"
50 #include "insets/insetbibtex.h"
51 #include "insets/insetinclude.h"
52 #include "insets/insettext.h"
53
54 #include "frontends/Alert.h"
55
56 #include "graphics/Previews.h"
57
58 #include "support/FileInfo.h"
59 #include "support/filetools.h"
60 #include "support/gzstream.h"
61 #include "support/lyxlib.h"
62 #include "support/os.h"
63 #include "support/path.h"
64 #include "support/textutils.h"
65 #include "support/tostr.h"
66
67 #include <boost/bind.hpp>
68
69 #include "support/std_sstream.h"
70
71 #include <iomanip>
72 #include <stack>
73
74 #include <utime.h>
75
76 #ifdef HAVE_LOCALE
77 #endif
78
79 using lyx::pos_type;
80
81 using lyx::support::AddName;
82 using lyx::support::atoi;
83 using lyx::support::bformat;
84 using lyx::support::ChangeExtension;
85 using lyx::support::cmd_ret;
86 using lyx::support::CreateBufferTmpDir;
87 using lyx::support::destroyDir;
88 using lyx::support::FileInfo;
89 using lyx::support::FileInfo;
90 using lyx::support::getExtFromContents;
91 using lyx::support::IsDirWriteable;
92 using lyx::support::IsFileWriteable;
93 using lyx::support::LibFileSearch;
94 using lyx::support::ltrim;
95 using lyx::support::MakeAbsPath;
96 using lyx::support::MakeDisplayPath;
97 using lyx::support::MakeLatexName;
98 using lyx::support::OnlyFilename;
99 using lyx::support::OnlyPath;
100 using lyx::support::Path;
101 using lyx::support::QuoteName;
102 using lyx::support::removeAutosaveFile;
103 using lyx::support::rename;
104 using lyx::support::RunCommand;
105 using lyx::support::split;
106 using lyx::support::strToInt;
107 using lyx::support::subst;
108 using lyx::support::tempName;
109 using lyx::support::trim;
110
111 namespace os = lyx::support::os;
112
113 using std::endl;
114 using std::for_each;
115 using std::make_pair;
116
117 using std::ifstream;
118 using std::ios;
119 using std::ostream;
120 using std::ostringstream;
121 using std::ofstream;
122 using std::pair;
123 using std::stack;
124 using std::vector;
125 using std::string;
126
127
128 // all these externs should eventually be removed.
129 extern BufferList bufferlist;
130
131 namespace {
132
133 const int LYX_FORMAT = 225;
134
135 } // namespace anon
136
137
138 typedef std::map<string, bool> DepClean;
139
140 struct Buffer::Impl
141 {
142         Impl(Buffer & parent, string const & file, bool readonly);
143
144         limited_stack<Undo> undostack;
145         limited_stack<Undo> redostack;
146         BufferParams params;
147         ParagraphList paragraphs;
148         LyXVC lyxvc;
149         string temppath;
150         bool nicefile;
151         TexRow texrow;
152
153         /// need to regenerate .tex ?
154         DepClean dep_clean;
155
156         /// is save needed
157         mutable bool lyx_clean;
158
159         /// is autosave needed
160         mutable bool bak_clean;
161
162         /// is this a unnamed file (New...)
163         bool unnamed;
164
165         /// buffer is r/o
166         bool read_only;
167
168         /// name of the file the buffer is associated with.
169         string filename;
170
171         /// The path to the document file.
172         string filepath;
173
174         boost::scoped_ptr<Messages> messages;
175
176         /** set to true only when the file is fully loaded.
177          *  Used to prevent the premature generation of previews
178          *  and by the citation inset.
179          */
180         bool file_fully_loaded;
181 };
182
183
184 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
185         : nicefile(true),
186           lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
187           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false)
188 {
189         lyxvc.buffer(&parent);
190         if (readonly_ || lyxrc.use_tempdir)
191                 temppath = CreateBufferTmpDir();
192 }
193
194
195 Buffer::Buffer(string const & file, bool ronly)
196         : pimpl_(new Impl(*this, file, ronly))
197 {
198         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
199 }
200
201
202 Buffer::~Buffer()
203 {
204         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
205         // here the buffer should take care that it is
206         // saved properly, before it goes into the void.
207
208         closing();
209
210         if (!temppath().empty() && destroyDir(temppath()) != 0) {
211                 Alert::warning(_("Could not remove temporary directory"),
212                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
213         }
214
215         paragraphs().clear();
216
217         // Remove any previewed LaTeX snippets associated with this buffer.
218         lyx::graphics::Previews::get().removeLoader(*this);
219 }
220
221
222 limited_stack<Undo> & Buffer::undostack()
223 {
224         return pimpl_->undostack;
225 }
226
227
228 limited_stack<Undo> const & Buffer::undostack() const
229 {
230         return pimpl_->undostack;
231 }
232
233
234 limited_stack<Undo> & Buffer::redostack()
235 {
236         return pimpl_->redostack;
237 }
238
239
240 limited_stack<Undo> const & Buffer::redostack() const
241 {
242         return pimpl_->redostack;
243 }
244
245
246 BufferParams & Buffer::params()
247 {
248         return pimpl_->params;
249 }
250
251
252 BufferParams const & Buffer::params() const
253 {
254         return pimpl_->params;
255 }
256
257
258 ParagraphList & Buffer::paragraphs()
259 {
260         return pimpl_->paragraphs;
261 }
262
263
264 ParagraphList const & Buffer::paragraphs() const
265 {
266         return pimpl_->paragraphs;
267 }
268
269
270 LyXVC & Buffer::lyxvc()
271 {
272         return pimpl_->lyxvc;
273 }
274
275
276 LyXVC const & Buffer::lyxvc() const
277 {
278         return pimpl_->lyxvc;
279 }
280
281
282 string const & Buffer::temppath() const
283 {
284         return pimpl_->temppath;
285 }
286
287
288 bool & Buffer::niceFile()
289 {
290         return pimpl_->nicefile;
291 }
292
293
294 bool Buffer::niceFile() const
295 {
296         return pimpl_->nicefile;
297 }
298
299
300 TexRow & Buffer::texrow()
301 {
302         return pimpl_->texrow;
303 }
304
305
306 TexRow const & Buffer::texrow() const
307 {
308         return pimpl_->texrow;
309 }
310
311
312 string const Buffer::getLatexName(bool no_path) const
313 {
314         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
315         return no_path ? OnlyFilename(name) : name;
316 }
317
318
319 pair<Buffer::LogType, string> const Buffer::getLogName() const
320 {
321         string const filename = getLatexName(false);
322
323         if (filename.empty())
324                 return make_pair(Buffer::latexlog, string());
325
326         string path = OnlyPath(filename);
327
328         if (lyxrc.use_tempdir || !IsDirWriteable(path))
329                 path = temppath();
330
331         string const fname = AddName(path,
332                                      OnlyFilename(ChangeExtension(filename,
333                                                                   ".log")));
334         string const bname =
335                 AddName(path, OnlyFilename(
336                         ChangeExtension(filename,
337                                         formats.extension("literate") + ".out")));
338
339         // If no Latex log or Build log is newer, show Build log
340
341         FileInfo const f_fi(fname);
342         FileInfo const b_fi(bname);
343
344         if (b_fi.exist() &&
345             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
346                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
347                 return make_pair(Buffer::buildlog, bname);
348         }
349         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
350         return make_pair(Buffer::latexlog, fname);
351 }
352
353
354 void Buffer::setReadonly(bool flag)
355 {
356         if (pimpl_->read_only != flag) {
357                 pimpl_->read_only = flag;
358                 readonly(flag);
359         }
360 }
361
362
363 void Buffer::setFileName(string const & newfile)
364 {
365         pimpl_->filename = MakeAbsPath(newfile);
366         pimpl_->filepath = OnlyPath(pimpl_->filename);
367         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
368         updateTitles();
369 }
370
371
372 // We'll remove this later. (Lgb)
373 namespace {
374
375 void unknownClass(string const & unknown)
376 {
377         Alert::warning(_("Unknown document class"),
378                 bformat(_("Using the default document class, because the "
379                         "class %1$s is unknown."), unknown));
380 }
381
382 } // anon
383
384 int Buffer::readHeader(LyXLex & lex)
385 {
386         int unknown_tokens = 0;
387
388         while (lex.isOK()) {
389                 lex.nextToken();
390                 string const token = lex.getString();
391
392                 if (token.empty())
393                         continue;
394
395                 if (token == "\\end_header")
396                         break;
397
398                 lyxerr[Debug::PARSER] << "Handling header token: `"
399                                       << token << '\'' << endl;
400
401
402                 string unknown = params().readToken(lex, token);
403                 if (!unknown.empty()) {
404                         if (unknown[0] != '\\') {
405                                 unknownClass(unknown);
406                         } else {
407                                 ++unknown_tokens;
408                                 string const s = bformat(_("Unknown token: "
409                                                            "%1$s %2$s\n"),
410                                                          token,
411                                                          lex.getString());
412                                 error(ErrorItem(_("Header error"), s,
413                                                 -1, 0, 0));
414                         }
415                 }
416         }
417         return unknown_tokens;
418 }
419
420
421 // candidate for move to BufferView
422 // (at least some parts in the beginning of the func)
423 //
424 // Uwe C. Schroeder
425 // changed to be public and have one parameter
426 // if par = 0 normal behavior
427 // else insert behavior
428 // Returns false if "\end_document" is not read (Asger)
429 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
430 {
431         Paragraph::depth_type depth = 0;
432         bool the_end_read = false;
433
434         if (paragraphs().empty()) {
435                 readHeader(lex);
436                 if (!params().getLyXTextClass().load()) {
437                         string theclass = params().getLyXTextClass().name();
438                         Alert::error(_("Can't load document class"), bformat(
439                                         "Using the default document class, because the "
440                                         " class %1$s could not be loaded.", theclass));
441                         params().textclass = 0;
442                 }
443         } else {
444                 // We don't want to adopt the parameters from the
445                 // document we insert, so read them into a temporary buffer
446                 // and then discard it
447
448                 Buffer tmpbuf("", false);
449                 tmpbuf.readHeader(lex);
450         }
451
452         while (lex.isOK()) {
453                 lex.nextToken();
454                 string const token = lex.getString();
455
456                 if (token.empty())
457                         continue;
458
459                 lyxerr[Debug::PARSER] << "Handling token: `"
460                                       << token << '\'' << endl;
461
462                 if (token == "\\end_document") {
463                         the_end_read = true;
464                         continue;
465                 }
466
467                 readParagraph(lex, token, paragraphs(), pit, depth);
468         }
469
470         return the_end_read;
471 }
472
473
474 int Buffer::readParagraph(LyXLex & lex, string const & token,
475                           ParagraphList & pars, ParagraphList::iterator & pit,
476                           lyx::depth_type & depth)
477 {
478         static Change current_change;
479         int unknown = 0;
480
481         if (token == "\\begin_layout") {
482                 lex.pushToken(token);
483
484                 Paragraph par;
485                 par.params().depth(depth);
486                 if (params().tracking_changes)
487                         par.trackChanges();
488                 LyXFont f(LyXFont::ALL_INHERIT, params().language);
489                 par.setFont(0, f);
490
491                 // insert after
492                 if (pit != pars.end())
493                         ++pit;
494
495                 pit = pars.insert(pit, par);
496
497                 // FIXME: goddamn InsetTabular makes us pass a Buffer
498                 // not BufferParams
499                 ::readParagraph(*this, *pit, lex);
500
501         } else if (token == "\\begin_deeper") {
502                 ++depth;
503         } else if (token == "\\end_deeper") {
504                 if (!depth) {
505                         lex.printError("\\end_deeper: " "depth is already null");
506                 } else {
507                         --depth;
508                 }
509         } else {
510                 ++unknown;
511         }
512         return unknown;
513 }
514
515
516 // needed to insert the selection
517 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
518                                  LyXFont const & fn,string const & str)
519 {
520         LyXLayout_ptr const & layout = par->layout();
521
522         LyXFont font = fn;
523
524         par->checkInsertChar(font);
525         // insert the string, don't insert doublespace
526         bool space_inserted = true;
527         bool autobreakrows = !par->inInset() ||
528                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
529         for(string::const_iterator cit = str.begin();
530             cit != str.end(); ++cit) {
531                 if (*cit == '\n') {
532                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
533                                 breakParagraph(params(), paragraphs(), par, pos,
534                                                layout->isEnvironment());
535                                 ++par;
536                                 pos = 0;
537                                 space_inserted = true;
538                         } else {
539                                 continue;
540                         }
541                         // do not insert consecutive spaces if !free_spacing
542                 } else if ((*cit == ' ' || *cit == '\t') &&
543                            space_inserted && !par->isFreeSpacing()) {
544                         continue;
545                 } else if (*cit == '\t') {
546                         if (!par->isFreeSpacing()) {
547                                 // tabs are like spaces here
548                                 par->insertChar(pos, ' ', font);
549                                 ++pos;
550                                 space_inserted = true;
551                         } else {
552                                 const pos_type nb = 8 - pos % 8;
553                                 for (pos_type a = 0; a < nb ; ++a) {
554                                         par->insertChar(pos, ' ', font);
555                                         ++pos;
556                                 }
557                                 space_inserted = true;
558                         }
559                 } else if (!IsPrintable(*cit)) {
560                         // Ignore unprintables
561                         continue;
562                 } else {
563                         // just insert the character
564                         par->insertChar(pos, *cit, font);
565                         ++pos;
566                         space_inserted = (*cit == ' ');
567                 }
568
569         }
570 }
571
572
573 bool Buffer::readFile(string const & filename)
574 {
575         // Check if the file is compressed.
576         string const format = getExtFromContents(filename);
577         if (format == "gzip" || format == "zip" || format == "compress") {
578                 params().compressed = true;
579         }
580
581         bool ret = readFile(filename, paragraphs().begin());
582
583         // After we have read a file, we must ensure that the buffer
584         // language is set and used in the gui.
585         // If you know of a better place to put this, please tell me. (Lgb)
586         updateDocLang(params().language);
587
588         return ret;
589 }
590
591
592 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
593 {
594         LyXLex lex(0, 0);
595         lex.setFile(filename);
596
597         return readFile(lex, filename, pit);
598 }
599
600
601 bool Buffer::fully_loaded() const
602 {
603         return pimpl_->file_fully_loaded;
604 }
605
606
607 void Buffer::fully_loaded(bool value)
608 {
609         pimpl_->file_fully_loaded = value;
610 }
611
612
613 bool Buffer::readFile(LyXLex & lex, string const & filename,
614                       ParagraphList::iterator pit)
615 {
616         BOOST_ASSERT(!filename.empty());
617
618         if (!lex.isOK()) {
619                 Alert::error(_("Document could not be read"),
620                              bformat(_("%1$s could not be read."), filename));
621                 return false;
622         }
623
624         lex.next();
625         string const token(lex.getString());
626
627         if (!lex.isOK()) {
628                 Alert::error(_("Document could not be read"),
629                              bformat(_("%1$s could not be read."), filename));
630                 return false;
631         }
632
633         // the first token _must_ be...
634         if (token != "\\lyxformat") {
635                 lyxerr << "Token: " << token << endl;
636
637                 Alert::error(_("Document format failure"),
638                              bformat(_("%1$s is not a LyX document."),
639                                        filename));
640                 return false;
641         }
642
643         lex.eatLine();
644         string tmp_format = lex.getString();
645         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
646         // if present remove ".," from string.
647         string::size_type dot = tmp_format.find_first_of(".,");
648         //lyxerr << "           dot found at " << dot << endl;
649         if (dot != string::npos)
650                         tmp_format.erase(dot, 1);
651         int file_format = strToInt(tmp_format);
652         //lyxerr << "format: " << file_format << endl;
653
654         if (file_format > LYX_FORMAT) {
655                 Alert::warning(_("Document format failure"),
656                                bformat(_("%1$s was created with a newer"
657                                          " version of LyX. This is likely to"
658                                          " cause problems."),
659                                          filename));
660         } else if (file_format < LYX_FORMAT) {
661                 string const tmpfile = tempName();
662                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
663                 if (command.empty()) {
664                         Alert::error(_("Conversion script not found"),
665                                      bformat(_("%1$s is from an earlier"
666                                                " version of LyX, but the"
667                                                " conversion script lyx2lyx"
668                                                " could not be found."),
669                                                filename));
670                         return false;
671                 }
672                 command += " -t"
673                         + tostr(LYX_FORMAT)
674                         + " -o " + tmpfile + ' '
675                         + QuoteName(filename);
676                 lyxerr[Debug::INFO] << "Running '"
677                                     << command << '\''
678                                     << endl;
679                 cmd_ret const ret = RunCommand(command);
680                 if (ret.first != 0) {
681                         Alert::error(_("Conversion script failed"),
682                                      bformat(_("%1$s is from an earlier version"
683                                               " of LyX, but the lyx2lyx script"
684                                               " failed to convert it."),
685                                               filename));
686                         return false;
687                 } else {
688                         bool ret = readFile(tmpfile, pit);
689                         // Do stuff with tmpfile name and buffer name here.
690                         return ret;
691                 }
692
693         }
694
695         bool the_end = readBody(lex, pit);
696         params().setPaperStuff();
697
698         if (!the_end) {
699                 Alert::error(_("Document format failure"),
700                              bformat(_("%1$s ended unexpectedly, which means"
701                                        " that it is probably corrupted."),
702                                        filename));
703         }
704         pimpl_->file_fully_loaded = true;
705         return true;
706 }
707
708
709 // Should probably be moved to somewhere else: BufferView? LyXView?
710 bool Buffer::save() const
711 {
712         // We don't need autosaves in the immediate future. (Asger)
713         resetAutosaveTimers();
714
715         // make a backup
716         string s;
717         if (lyxrc.make_backup) {
718                 s = fileName() + '~';
719                 if (!lyxrc.backupdir_path.empty())
720                         s = AddName(lyxrc.backupdir_path,
721                                     subst(os::slashify_path(s),'/','!'));
722
723                 // Rename is the wrong way of making a backup,
724                 // this is the correct way.
725                 /* truss cp fil fil2:
726                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
727                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
728                    open("LyXVC.lyx", O_RDONLY)                     = 3
729                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
730                    fstat(4, 0xEFFFF508)                            = 0
731                    fstat(3, 0xEFFFF508)                            = 0
732                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
733                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
734                    read(3, 0xEFFFD4A0, 8192)                       = 0
735                    close(4)                                        = 0
736                    close(3)                                        = 0
737                    chmod("LyXVC3.lyx", 0100644)                    = 0
738                    lseek(0, 0, SEEK_CUR)                           = 46440
739                    _exit(0)
740                 */
741
742                 // Should probably have some more error checking here.
743                 // Doing it this way, also makes the inodes stay the same.
744                 // This is still not a very good solution, in particular we
745                 // might loose the owner of the backup.
746                 FileInfo finfo(fileName());
747                 if (finfo.exist()) {
748                         mode_t fmode = finfo.getMode();
749                         struct utimbuf times = {
750                                 finfo.getAccessTime(),
751                                 finfo.getModificationTime() };
752
753                         ifstream ifs(fileName().c_str());
754                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
755                         if (ifs && ofs) {
756                                 ofs << ifs.rdbuf();
757                                 ifs.close();
758                                 ofs.close();
759                                 ::chmod(s.c_str(), fmode);
760
761                                 if (::utime(s.c_str(), &times)) {
762                                         lyxerr << "utime error." << endl;
763                                 }
764                         } else {
765                                 lyxerr << "LyX was not able to make "
766                                         "backup copy. Beware." << endl;
767                         }
768                 }
769         }
770
771         if (writeFile(fileName())) {
772                 markClean();
773                 removeAutosaveFile(fileName());
774         } else {
775                 // Saving failed, so backup is not backup
776                 if (lyxrc.make_backup) {
777                         rename(s, fileName());
778                 }
779                 return false;
780         }
781         return true;
782 }
783
784
785 bool Buffer::writeFile(string const & fname) const
786 {
787         if (pimpl_->read_only && (fname == fileName())) {
788                 return false;
789         }
790
791         FileInfo finfo(fname);
792         if (finfo.exist() && !finfo.writable()) {
793                 return false;
794         }
795
796         bool retval;
797
798         if (params().compressed) {
799                 gz::ogzstream ofs(fname.c_str());
800
801                 if (!ofs)
802                         return false;
803
804                 retval = do_writeFile(ofs);
805
806         } else {
807                 ofstream ofs(fname.c_str());
808                 if (!ofs)
809                         return false;
810
811                 retval = do_writeFile(ofs);
812         }
813
814         return retval;
815 }
816
817
818 bool Buffer::do_writeFile(ostream & ofs) const
819 {
820
821 #ifdef HAVE_LOCALE
822         // Use the standard "C" locale for file output.
823         ofs.imbue(std::locale::classic());
824 #endif
825
826         // The top of the file should not be written by params().
827
828         // write out a comment in the top of the file
829         ofs << "#LyX " << lyx_version
830             << " created this file. For more info see http://www.lyx.org/\n"
831             << "\\lyxformat " << LYX_FORMAT << "\n";
832
833         // now write out the buffer paramters.
834         params().writeFile(ofs);
835
836         ofs << "\\end_header\n";
837
838         Paragraph::depth_type depth = 0;
839
840         // this will write out all the paragraphs
841         // using recursive descent.
842         ParagraphList::const_iterator pit = paragraphs().begin();
843         ParagraphList::const_iterator pend = paragraphs().end();
844         for (; pit != pend; ++pit)
845                 pit->write(*this, ofs, params(), depth);
846
847         // Write marker that shows file is complete
848         ofs << "\n\\end_document" << endl;
849
850         // Shouldn't really be needed....
851         //ofs.close();
852
853         // how to check if close went ok?
854         // Following is an attempt... (BE 20001011)
855
856         // good() returns false if any error occured, including some
857         //        formatting error.
858         // bad()  returns true if something bad happened in the buffer,
859         //        which should include file system full errors.
860
861         bool status = true;
862         if (!ofs.good()) {
863                 status = false;
864 #if 0
865                 if (ofs.bad()) {
866                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
867                 } else {
868                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
869                                << endl;
870                 }
871 #endif
872         }
873
874         return status;
875 }
876
877
878 void Buffer::makeLaTeXFile(string const & fname,
879                            string const & original_path,
880                            OutputParams const & runparams,
881                            bool output_preamble, bool output_body)
882 {
883         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
884
885         ofstream ofs;
886         if (!openFileWrite(ofs, fname))
887                 return;
888
889         makeLaTeXFile(ofs, original_path,
890                       runparams, output_preamble, output_body);
891
892         ofs.close();
893         if (ofs.fail()) {
894                 lyxerr << "File was not closed properly." << endl;
895         }
896 }
897
898
899 void Buffer::makeLaTeXFile(ostream & os,
900                            string const & original_path,
901                            OutputParams const & runparams_in,
902                            bool output_preamble, bool output_body)
903 {
904         OutputParams runparams = runparams_in;
905         niceFile() = runparams.nice; // this will be used by Insetincludes.
906
907         // validate the buffer.
908         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
909         LaTeXFeatures features(*this, params());
910         validate(features);
911         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
912
913         texrow().reset();
914         // The starting paragraph of the coming rows is the
915         // first paragraph of the document. (Asger)
916         texrow().start(paragraphs().begin()->id(), 0);
917
918         if (output_preamble && runparams.nice) {
919                 os << "%% LyX " << lyx_version << " created this file.  "
920                         "For more info, see http://www.lyx.org/.\n"
921                         "%% Do not edit unless you really know what "
922                         "you are doing.\n";
923                 texrow().newline();
924                 texrow().newline();
925         }
926         lyxerr[Debug::INFO] << "lyx header finished" << endl;
927         // There are a few differences between nice LaTeX and usual files:
928         // usual is \batchmode and has a
929         // special input@path to allow the including of figures
930         // with either \input or \includegraphics (what figinsets do).
931         // input@path is set when the actual parameter
932         // original_path is set. This is done for usual tex-file, but not
933         // for nice-latex-file. (Matthias 250696)
934         if (output_preamble) {
935                 if (!runparams.nice) {
936                         // code for usual, NOT nice-latex-file
937                         os << "\\batchmode\n"; // changed
938                         // from \nonstopmode
939                         texrow().newline();
940                 }
941                 if (!original_path.empty()) {
942                         string inputpath = os::external_path(original_path);
943                         subst(inputpath, "~", "\\string~");
944                         os << "\\makeatletter\n"
945                             << "\\def\\input@path{{"
946                             << inputpath << "/}}\n"
947                             << "\\makeatother\n";
948                         texrow().newline();
949                         texrow().newline();
950                         texrow().newline();
951                 }
952
953                 // Write the preamble
954                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
955
956                 if (!output_body)
957                         return;
958
959                 // make the body.
960                 os << "\\begin{document}\n";
961                 texrow().newline();
962         } // output_preamble
963         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
964
965         if (!lyxrc.language_auto_begin) {
966                 os << subst(lyxrc.language_command_begin, "$$lang",
967                              params().language->babel())
968                     << endl;
969                 texrow().newline();
970         }
971
972         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
973
974         // add this just in case after all the paragraphs
975         os << endl;
976         texrow().newline();
977
978         if (!lyxrc.language_auto_end) {
979                 os << subst(lyxrc.language_command_end, "$$lang",
980                              params().language->babel())
981                     << endl;
982                 texrow().newline();
983         }
984
985         if (output_preamble) {
986                 os << "\\end{document}\n";
987                 texrow().newline();
988
989                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
990         } else {
991                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
992                                      << endl;
993         }
994
995         // Just to be sure. (Asger)
996         texrow().newline();
997
998         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
999         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1000                             << '.' << endl;
1001
1002         // we want this to be true outside previews (for insetexternal)
1003         niceFile() = true;
1004 }
1005
1006
1007 bool Buffer::isLatex() const
1008 {
1009         return params().getLyXTextClass().outputType() == LATEX;
1010 }
1011
1012
1013 bool Buffer::isLinuxDoc() const
1014 {
1015         return params().getLyXTextClass().outputType() == LINUXDOC;
1016 }
1017
1018
1019 bool Buffer::isLiterate() const
1020 {
1021         return params().getLyXTextClass().outputType() == LITERATE;
1022 }
1023
1024
1025 bool Buffer::isDocBook() const
1026 {
1027         return params().getLyXTextClass().outputType() == DOCBOOK;
1028 }
1029
1030
1031 bool Buffer::isSGML() const
1032 {
1033         LyXTextClass const & tclass = params().getLyXTextClass();
1034
1035         return tclass.outputType() == LINUXDOC ||
1036                tclass.outputType() == DOCBOOK;
1037 }
1038
1039
1040 void Buffer::makeLinuxDocFile(string const & fname,
1041                               OutputParams const & runparams,
1042                               bool body_only )
1043 {
1044         ofstream ofs;
1045         if (!openFileWrite(ofs, fname))
1046                 return;
1047
1048         niceFile() = runparams.nice; // this will be used by included files.
1049
1050         LaTeXFeatures features(*this, params());
1051
1052         validate(features);
1053
1054         texrow().reset();
1055
1056         LyXTextClass const & tclass = params().getLyXTextClass();
1057
1058         string top_element = tclass.latexname();
1059
1060         if (!body_only) {
1061                 ofs << "<!doctype linuxdoc system";
1062
1063                 string preamble = params().preamble;
1064                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1065                          : fname;
1066                 preamble += features.getIncludedFiles(name);
1067                 preamble += features.getLyXSGMLEntities();
1068
1069                 if (!preamble.empty()) {
1070                         ofs << " [ " << preamble << " ]";
1071                 }
1072                 ofs << ">\n\n";
1073
1074                 if (params().options.empty())
1075                         sgml::openTag(ofs, 0, false, top_element);
1076                 else {
1077                         string top = top_element;
1078                         top += ' ';
1079                         top += params().options;
1080                         sgml::openTag(ofs, 0, false, top);
1081                 }
1082         }
1083
1084         ofs << "<!-- LyX "  << lyx_version
1085             << " created this file. For more info see http://www.lyx.org/"
1086             << " -->\n";
1087
1088         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1089
1090         if (!body_only) {
1091                 ofs << "\n\n";
1092                 sgml::closeTag(ofs, 0, false, top_element);
1093         }
1094
1095         ofs.close();
1096         // How to check for successful close
1097
1098         // we want this to be true outside previews (for insetexternal)
1099         niceFile() = true;
1100 }
1101
1102
1103 void Buffer::makeDocBookFile(string const & fname,
1104                              OutputParams const & runparams,
1105                              bool only_body)
1106 {
1107         ofstream ofs;
1108         if (!openFileWrite(ofs, fname))
1109                 return;
1110
1111         niceFile() = runparams.nice; // this will be used by Insetincludes.
1112
1113         LaTeXFeatures features(*this, params());
1114         validate(features);
1115
1116         texrow().reset();
1117
1118         LyXTextClass const & tclass = params().getLyXTextClass();
1119         string top_element = tclass.latexname();
1120
1121         if (!only_body) {
1122                 ofs << "<!DOCTYPE " << top_element
1123                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1124
1125                 string preamble = params().preamble;
1126                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1127                          : fname;
1128                 preamble += features.getIncludedFiles(name);
1129                 preamble += features.getLyXSGMLEntities();
1130
1131                 if (!preamble.empty()) {
1132                         ofs << "\n [ " << preamble << " ]";
1133                 }
1134                 ofs << ">\n\n";
1135         }
1136
1137         string top = top_element;
1138         top += " lang=\"";
1139         top += params().language->code();
1140         top += '"';
1141
1142         if (!params().options.empty()) {
1143                 top += ' ';
1144                 top += params().options;
1145         }
1146         sgml::openTag(ofs, 0, false, top);
1147
1148         ofs << "<!-- DocBook file was created by LyX " << lyx_version
1149             << "\n  See http://www.lyx.org/ for more information -->\n";
1150
1151         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1152
1153         ofs << "\n\n";
1154         sgml::closeTag(ofs, 0, false, top_element);
1155
1156         ofs.close();
1157         // How to check for successful close
1158
1159         // we want this to be true outside previews (for insetexternal)
1160         niceFile() = true;
1161 }
1162
1163
1164 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1165 // Other flags: -wall -v0 -x
1166 int Buffer::runChktex()
1167 {
1168         busy(true);
1169
1170         // get LaTeX-Filename
1171         string const name = getLatexName();
1172         string path = filePath();
1173
1174         string const org_path = path;
1175         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1176                 path = temppath();
1177         }
1178
1179         Path p(path); // path to LaTeX file
1180         message(_("Running chktex..."));
1181
1182         // Generate the LaTeX file if neccessary
1183         OutputParams runparams;
1184         runparams.flavor = OutputParams::LATEX;
1185         runparams.nice = false;
1186         makeLaTeXFile(name, org_path, runparams);
1187
1188         TeXErrors terr;
1189         Chktex chktex(lyxrc.chktex_command, name, filePath());
1190         int res = chktex.run(terr); // run chktex
1191
1192         if (res == -1) {
1193                 Alert::error(_("chktex failure"),
1194                              _("Could not run chktex successfully."));
1195         } else if (res > 0) {
1196                 // Insert all errors as errors boxes
1197                 bufferErrors(*this, terr);
1198         }
1199
1200         busy(false);
1201
1202         return res;
1203 }
1204
1205
1206 void Buffer::validate(LaTeXFeatures & features) const
1207 {
1208         LyXTextClass const & tclass = params().getLyXTextClass();
1209
1210         if (params().tracking_changes) {
1211                 features.require("dvipost");
1212                 features.require("color");
1213         }
1214
1215         // AMS Style is at document level
1216         if (params().use_amsmath == BufferParams::AMS_ON
1217             || tclass.provides(LyXTextClass::amsmath))
1218                 features.require("amsmath");
1219
1220         for_each(paragraphs().begin(), paragraphs().end(),
1221                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1222
1223         // the bullet shapes are buffer level not paragraph level
1224         // so they are tested here
1225         for (int i = 0; i < 4; ++i) {
1226                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1227                         int const font = params().user_defined_bullet(i).getFont();
1228                         if (font == 0) {
1229                                 int const c = params()
1230                                         .user_defined_bullet(i)
1231                                         .getCharacter();
1232                                 if (c == 16
1233                                    || c == 17
1234                                    || c == 25
1235                                    || c == 26
1236                                    || c == 31) {
1237                                         features.require("latexsym");
1238                                 }
1239                         } else if (font == 1) {
1240                                 features.require("amssymb");
1241                         } else if ((font >= 2 && font <= 5)) {
1242                                 features.require("pifont");
1243                         }
1244                 }
1245         }
1246
1247         if (lyxerr.debugging(Debug::LATEX)) {
1248                 features.showStruct();
1249         }
1250 }
1251
1252
1253 void Buffer::getLabelList(std::vector<string> & list) const
1254 {
1255         /// if this is a child document and the parent is already loaded
1256         /// Use the parent's list instead  [ale990407]
1257         if (!params().parentname.empty()
1258             && bufferlist.exists(params().parentname)) {
1259                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1260                 if (tmp) {
1261                         tmp->getLabelList(list);
1262                         return;
1263                 }
1264         }
1265
1266         for (inset_iterator it = inset_const_iterator_begin();
1267              it != inset_const_iterator_end(); ++it) {
1268                 it->getLabelList(*this, list);
1269         }
1270 }
1271
1272
1273 // This is also a buffer property (ale)
1274 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1275 {
1276         /// if this is a child document and the parent is already loaded
1277         /// use the parent's list instead  [ale990412]
1278         if (!params().parentname.empty() &&
1279             bufferlist.exists(params().parentname)) {
1280                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1281                 if (tmp) {
1282                         tmp->fillWithBibKeys(keys);
1283                         return;
1284                 }
1285         }
1286
1287         for (inset_iterator it = inset_const_iterator_begin();
1288                 it != inset_const_iterator_end(); ++it) {
1289                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1290                         InsetBibtex const & inset =
1291                                 dynamic_cast<InsetBibtex const &>(*it);
1292                         inset.fillWithBibKeys(*this, keys);
1293                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1294                         InsetInclude const & inset =
1295                                 dynamic_cast<InsetInclude const &>(*it);
1296                         inset.fillWithBibKeys(*this, keys);
1297                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1298                         InsetBibitem const & inset =
1299                                 dynamic_cast<InsetBibitem const &>(*it);
1300                         string const key = inset.getContents();
1301                         string const opt = inset.getOptions();
1302                         string const ref; // = pit->asString(this, false);
1303                         string const info = opt + "TheBibliographyRef" + ref;
1304                         keys.push_back(pair<string, string>(key, info));
1305                 }
1306         }
1307 }
1308
1309
1310 bool Buffer::isDepClean(string const & name) const
1311 {
1312         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1313         if (it == pimpl_->dep_clean.end())
1314                 return true;
1315         return it->second;
1316 }
1317
1318
1319 void Buffer::markDepClean(string const & name)
1320 {
1321         pimpl_->dep_clean[name] = true;
1322 }
1323
1324
1325 bool Buffer::dispatch(string const & command, bool * result)
1326 {
1327         return dispatch(lyxaction.lookupFunc(command), result);
1328 }
1329
1330
1331 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1332 {
1333         bool dispatched = true;
1334
1335         switch (func.action) {
1336                 case LFUN_EXPORT: {
1337                         bool const tmp = Exporter::Export(this, func.argument, false);
1338                         if (result)
1339                                 *result = tmp;
1340                         break;
1341                 }
1342
1343                 default:
1344                         dispatched = false;
1345         }
1346         return dispatched;
1347 }
1348
1349
1350 void Buffer::changeLanguage(Language const * from, Language const * to)
1351 {
1352         lyxerr << "Changing Language!" << endl;
1353
1354         // Take care of l10n/i18n
1355         updateDocLang(to);
1356
1357         ParIterator end = par_iterator_end();
1358         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1359                 it->changeLanguage(params(), from, to);
1360 }
1361
1362
1363 void Buffer::updateDocLang(Language const * nlang)
1364 {
1365         pimpl_->messages.reset(new Messages(nlang->code()));
1366 }
1367
1368
1369 bool Buffer::isMultiLingual()
1370 {
1371         ParIterator end = par_iterator_end();
1372         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1373                 if (it->isMultiLingual(params()))
1374                         return true;
1375
1376         return false;
1377 }
1378
1379
1380 void Buffer::inset_iterator::setParagraph()
1381 {
1382         while (pit != pend) {
1383                 it = pit->insetlist.begin();
1384                 if (it != pit->insetlist.end())
1385                         return;
1386                 ++pit;
1387         }
1388 }
1389
1390
1391 ParIterator Buffer::getParFromID(int id) const
1392 {
1393 #warning FIXME: const correctness! (Andre)
1394         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1395         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1396
1397 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1398         if (id < 0) {
1399                 // John says this is called with id == -1 from undo
1400                 lyxerr << "getParFromID(), id: " << id << endl;
1401                 return end;
1402         }
1403
1404         for (; it != end; ++it)
1405                 if (it->id() == id)
1406                         return it;
1407
1408         return end;
1409 }
1410
1411
1412 bool Buffer::hasParWithID(int id) const
1413 {
1414         ParConstIterator it = par_iterator_begin();
1415         ParConstIterator end = par_iterator_end();
1416
1417         if (id < 0) {
1418                 // John says this is called with id == -1 from undo
1419                 lyxerr << "hasParWithID(), id: " << id << endl;
1420                 return 0;
1421         }
1422
1423         for (; it != end; ++it)
1424                 if (it->id() == id)
1425                         return true;
1426
1427         return false;
1428 }
1429
1430
1431 PosIterator Buffer::pos_iterator_begin()
1432 {
1433         return PosIterator(&paragraphs(), paragraphs().begin(), 0);
1434 }
1435
1436
1437 PosIterator Buffer::pos_iterator_end()
1438 {
1439         return PosIterator(&paragraphs(), paragraphs().end(), 0);
1440 }
1441
1442
1443 ParIterator Buffer::par_iterator_begin()
1444 {
1445         return ParIterator(paragraphs().begin(), paragraphs());
1446 }
1447
1448
1449 ParIterator Buffer::par_iterator_end()
1450 {
1451         return ParIterator(paragraphs().end(), paragraphs());
1452 }
1453
1454
1455 ParConstIterator Buffer::par_iterator_begin() const
1456 {
1457         ParagraphList const & pars = paragraphs();
1458         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1459 }
1460
1461
1462 ParConstIterator Buffer::par_iterator_end() const
1463 {
1464         ParagraphList const & pars = paragraphs();
1465         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1466 }
1467
1468
1469 Language const * Buffer::getLanguage() const
1470 {
1471         return params().language;
1472 }
1473
1474
1475 string const Buffer::B_(string const & l10n) const
1476 {
1477         if (pimpl_->messages.get()) {
1478                 return pimpl_->messages->get(l10n);
1479         }
1480
1481         return _(l10n);
1482 }
1483
1484
1485 bool Buffer::isClean() const
1486 {
1487         return pimpl_->lyx_clean;
1488 }
1489
1490
1491 bool Buffer::isBakClean() const
1492 {
1493         return pimpl_->bak_clean;
1494 }
1495
1496
1497 void Buffer::markClean() const
1498 {
1499         if (!pimpl_->lyx_clean) {
1500                 pimpl_->lyx_clean = true;
1501                 updateTitles();
1502         }
1503         // if the .lyx file has been saved, we don't need an
1504         // autosave
1505         pimpl_->bak_clean = true;
1506 }
1507
1508
1509 void Buffer::markBakClean()
1510 {
1511         pimpl_->bak_clean = true;
1512 }
1513
1514
1515 void Buffer::setUnnamed(bool flag)
1516 {
1517         pimpl_->unnamed = flag;
1518 }
1519
1520
1521 bool Buffer::isUnnamed()
1522 {
1523         return pimpl_->unnamed;
1524 }
1525
1526
1527 void Buffer::markDirty()
1528 {
1529         if (pimpl_->lyx_clean) {
1530                 pimpl_->lyx_clean = false;
1531                 updateTitles();
1532         }
1533         pimpl_->bak_clean = false;
1534
1535         DepClean::iterator it = pimpl_->dep_clean.begin();
1536         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1537
1538         for (; it != end; ++it) {
1539                 it->second = false;
1540         }
1541 }
1542
1543
1544 string const & Buffer::fileName() const
1545 {
1546         return pimpl_->filename;
1547 }
1548
1549
1550 string const & Buffer::filePath() const
1551 {
1552         return pimpl_->filepath;
1553 }
1554
1555
1556 bool Buffer::isReadonly() const
1557 {
1558         return pimpl_->read_only;
1559 }
1560
1561
1562 void Buffer::setParentName(string const & name)
1563 {
1564         params().parentname = name;
1565 }
1566
1567
1568 Buffer::inset_iterator::inset_iterator()
1569         : pit(), pend()
1570 {}
1571
1572
1573 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1574         : pit(p), pend(e)
1575 {
1576         setParagraph();
1577 }
1578
1579
1580 Buffer::inset_iterator Buffer::inset_iterator_begin()
1581 {
1582         return inset_iterator(paragraphs().begin(), paragraphs().end());
1583 }
1584
1585
1586 Buffer::inset_iterator Buffer::inset_iterator_end()
1587 {
1588         return inset_iterator(paragraphs().end(), paragraphs().end());
1589 }
1590
1591
1592 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1593 {
1594         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1595         return inset_iterator(pars.begin(), pars.end());
1596 }
1597
1598
1599 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1600 {
1601         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1602         return inset_iterator(pars.end(), pars.end());
1603 }
1604
1605
1606 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1607 {
1608         if (pit != pend) {
1609                 ++it;
1610                 if (it == pit->insetlist.end()) {
1611                         ++pit;
1612                         setParagraph();
1613                 }
1614         }
1615         return *this;
1616 }
1617
1618
1619 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1620 {
1621         inset_iterator tmp = *this;
1622         ++*this;
1623         return tmp;
1624 }
1625
1626
1627 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1628 {
1629         return *it->inset;
1630 }
1631
1632
1633 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1634 {
1635         return it->inset;
1636 }
1637
1638
1639 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1640 {
1641         return pit;
1642 }
1643
1644
1645 lyx::pos_type Buffer::inset_iterator::getPos() const
1646 {
1647         return it->pos;
1648 }
1649
1650
1651 bool operator==(Buffer::inset_iterator const & iter1,
1652                 Buffer::inset_iterator const & iter2)
1653 {
1654         return iter1.pit == iter2.pit
1655                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1656 }
1657
1658
1659 bool operator!=(Buffer::inset_iterator const & iter1,
1660                 Buffer::inset_iterator const & iter2)
1661 {
1662         return !(iter1 == iter2);
1663 }