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