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