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