]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
f4f33d46cf3a7c88f38c405bc351a646fb8fa72f
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19 #include "support/SignalSlot.h"
20
21 #include <string>
22 #include <vector>
23
24
25 namespace lyx {
26
27 class BiblioInfo;
28 class BufferParams;
29 class BufferSet;
30 class DocIterator;
31 class ErrorItem;
32 class ErrorList;
33 class FuncRequest;
34 class Inset;
35 class InsetRef;
36 class InsetLabel;
37 class Font;
38 class Format;
39 class Lexer;
40 class LyXRC;
41 class Text;
42 class LyXVC;
43 class LaTeXFeatures;
44 class Language;
45 class MacroData;
46 class MacroNameSet;
47 class MacroSet;
48 class OutputParams;
49 class Paragraph;
50 class ParConstIterator;
51 class ParIterator;
52 class ParagraphList;
53 class TeXErrors;
54 class TexRow;
55 class TocBackend;
56 class Undo;
57
58 namespace frontend {
59 class GuiBufferDelegate;
60 class WorkAreaManager;
61 }
62
63 namespace support {
64 class FileName;
65 class FileNameList;
66 }
67
68 /** The buffer object.
69  * This is the buffer object. It contains all the informations about
70  * a document loaded into LyX.
71  * The buffer object owns the Text (wrapped in an InsetText), which
72  * contains the individual paragraphs of the document.
73  *
74  *
75  * I am not sure if the class is complete or
76  * minimal, probably not.
77  * \author Lars Gullik Bjønnes
78  */
79 class Buffer {
80 public:
81         /// What type of log will \c getLogName() return?
82         enum LogType {
83                 latexlog, ///< LaTeX log
84                 buildlog  ///< Literate build log
85         };
86
87         /// Result of \c readFile()
88         enum ReadStatus {
89                 failure, ///< The file could not be read
90                 success, ///< The file could not be read
91                 wrongversion ///< The version of the file does not match ours
92         };
93
94
95         /// Method to check if a file is externally modified, used by
96         /// isExternallyModified()
97         /**
98          * timestamp is fast but inaccurate. For example, the granularity
99          * of timestamp on a FAT filesystem is 2 second. Also, various operations
100          * may touch the timestamp of a file even when its content is unchanged.
101          *
102          * checksum is accurate but slow, which can be a problem when it is
103          * frequently used, or used for a large file on a slow (network) file
104          * system.
105          *
106          * FIXME: replace this method with support/FileMonitor.
107          */
108         enum CheckMethod {
109                 checksum_method,  ///< Use file checksum
110                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
111         };
112
113         /// Constructor
114         explicit Buffer(std::string const & file, bool b = false);
115
116         /// Destructor
117         ~Buffer();
118
119         /** High-level interface to buffer functionality.
120             This function parses a command string and executes it
121         */
122         bool dispatch(std::string const & command, bool * result = 0);
123
124         /// Maybe we know the function already by number...
125         bool dispatch(FuncRequest const & func, bool * result = 0);
126
127         /// Load the autosaved file.
128         void loadAutoSaveFile();
129
130         /// read a new document from a string
131         bool readString(std::string const &);
132         /// load a new file
133         bool readFile(support::FileName const & filename);
134
135         /// read the header, returns number of unknown tokens
136         int readHeader(Lexer & lex);
137
138         /** Reads a file without header.
139             \param par if != 0 insert the file.
140             \return \c true if file is not completely read.
141         */
142         bool readDocument(Lexer &);
143
144         ///
145         void insertStringAsLines(ParagraphList & plist,
146                 pit_type &, pos_type &,
147                 Font const &, docstring const &, bool);
148         ///
149         DocIterator getParFromID(int id) const;
150         /// do we have a paragraph with this id?
151         bool hasParWithID(int id) const;
152
153         ///
154         frontend::WorkAreaManager & workAreaManager() const;
155
156         /** Save file.
157             Takes care of auto-save files and backup file if requested.
158             Returns \c true if the save is successful, \c false otherwise.
159         */
160         bool save() const;
161
162         /// Write document to stream. Returns \c false if unsuccesful.
163         bool write(std::ostream &) const;
164         /// Write file. Returns \c false if unsuccesful.
165         bool writeFile(support::FileName const &) const;
166
167         /// Loads LyX file \c filename into buffer, *  and \return success
168         bool loadLyXFile(support::FileName const & s);
169
170         /// Fill in the ErrorList with the TeXErrors
171         void bufferErrors(TeXErrors const &, ErrorList &) const;
172
173         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
174         bool makeLaTeXFile(support::FileName const & filename,
175                            std::string const & original_path,
176                            OutputParams const &,
177                            bool output_preamble = true,
178                            bool output_body = true) const;
179         /** Export the buffer to LaTeX.
180             If \p os is a file stream, and params().inputenc is "auto" or
181             "default", and the buffer contains text in different languages
182             with more than one encoding, then this method will change the
183             encoding associated to \p os. Therefore you must not call this
184             method with a string stream if the output is supposed to go to a
185             file. \code
186             ofdocstream ofs;
187             ofs.open("test.tex");
188             writeLaTeXSource(ofs, ...);
189             ofs.close();
190             \endcode is NOT equivalent to \code
191             odocstringstream oss;
192             writeLaTeXSource(oss, ...);
193             ofdocstream ofs;
194             ofs.open("test.tex");
195             ofs << oss.str();
196             ofs.close();
197             \endcode
198          */
199         void writeLaTeXSource(odocstream & os,
200                            std::string const & original_path,
201                            OutputParams const &,
202                            bool output_preamble = true,
203                            bool output_body = true) const;
204         ///
205         void makeDocBookFile(support::FileName const & filename,
206                              OutputParams const & runparams_in,
207                              bool only_body = false) const;
208         ///
209         void writeDocBookSource(odocstream & os, std::string const & filename,
210                              OutputParams const & runparams_in,
211                              bool only_body = false) const;
212         /// returns the main language for the buffer (document)
213         Language const * language() const;
214         /// get l10n translated to the buffers language
215         docstring const B_(std::string const & l10n) const;
216
217         ///
218         int runChktex();
219         /// return true if the main lyx file does not need saving
220         bool isClean() const;
221         ///
222         bool isBakClean() const;
223         ///
224         bool isDepClean(std::string const & name) const;
225
226         /// whether or not disk file has been externally modified
227         bool isExternallyModified(CheckMethod method) const;
228
229         /// save timestamp and checksum of the given file.
230         void saveCheckSum(support::FileName const & file) const;
231
232         /// mark the main lyx file as not needing saving
233         void markClean() const;
234
235         ///
236         void markBakClean() const;
237
238         ///
239         void markDepClean(std::string const & name);
240
241         ///
242         void setUnnamed(bool flag = true);
243
244         ///
245         bool isUnnamed() const;
246
247         /// Mark this buffer as dirty.
248         void markDirty();
249
250         /// Returns the buffer's filename. It is always an absolute path.
251         support::FileName fileName() const;
252
253         /// Returns the buffer's filename. It is always an absolute path.
254         std::string absFileName() const;
255
256         /// Returns the the path where the buffer lives.
257         /// It is always an absolute path.
258         std::string filePath() const;
259
260         /** A transformed version of the file name, adequate for LaTeX.
261             \param no_path optional if \c true then the path is stripped.
262         */
263         std::string latexName(bool no_path = true) const;
264
265         /// Get thee name and type of the log.
266         std::string logName(LogType * type = 0) const;
267
268         /// Change name of buffer. Updates "read-only" flag.
269         void setFileName(std::string const & newfile);
270
271         /// Set document's parent Buffer.
272         void setParent(Buffer const *);
273         Buffer const * parent() const;
274
275         // Collect all relative buffer
276         std::vector<Buffer const *> allRelatives() const;
277
278         /** Get the document's master (or \c this if this is not a
279             child document)
280          */
281         Buffer const * masterBuffer() const;
282
283         /// \return true if \p child is a child of this \c Buffer.
284         bool isChild(Buffer * child) const;
285
286         /// Is buffer read-only?
287         bool isReadonly() const;
288
289         /// Set buffer read-only flag
290         void setReadonly(bool flag = true);
291
292         /// returns \c true if the buffer contains a LaTeX document
293         bool isLatex() const;
294         /// returns \c true if the buffer contains a DocBook document
295         bool isDocBook() const;
296         /// returns \c true if the buffer contains a Wed document
297         bool isLiterate() const;
298
299         /** Validate a buffer for LaTeX.
300             This validates the buffer, and returns a struct for use by
301             #makeLaTeX# and others. Its main use is to figure out what
302             commands and packages need to be included in the LaTeX file.
303             It (should) also check that the needed constructs are there
304             (i.e. that the \refs points to coresponding \labels). It
305             should perhaps inset "error" insets to help the user correct
306             obvious mistakes.
307         */
308         void validate(LaTeXFeatures &) const;
309
310         /// Update the cache with all bibfiles in use (including bibfiles
311         /// of loaded child documents).
312         void updateBibfilesCache() const;
313         ///
314         void invalidateBibinfoCache();
315         /// Return the cache with all bibfiles in use (including bibfiles
316         /// of loaded child documents).
317         support::FileNameList const & getBibfilesCache() const;
318         /// \return the bibliography information for this buffer's master,
319         /// or just for it, if it isn't a child.
320         BiblioInfo const & masterBibInfo() const;
321         /// \return the bibliography information for this buffer ONLY.
322         BiblioInfo const & localBibInfo() const;
323         ///
324         void getLabelList(std::vector<docstring> &) const;
325
326         ///
327         void changeLanguage(Language const * from, Language const * to);
328
329         ///
330         bool isMultiLingual() const;
331
332         ///
333         BufferParams & params();
334         BufferParams const & params() const;
335
336         /** The list of paragraphs.
337             This is a linked list of paragraph, this list holds the
338             whole contents of the document.
339          */
340         ParagraphList & paragraphs();
341         ParagraphList const & paragraphs() const;
342
343         /// LyX version control object.
344         LyXVC & lyxvc();
345         LyXVC const & lyxvc() const;
346
347         /// Where to put temporary files.
348         std::string const temppath() const;
349
350         /// Used when typesetting to place errorboxes.
351         TexRow const & texrow() const;
352         TexRow & texrow();
353
354         ///
355         ParIterator par_iterator_begin();
356         ///
357         ParConstIterator par_iterator_begin() const;
358         ///
359         ParIterator par_iterator_end();
360         ///
361         ParConstIterator par_iterator_end() const;
362
363         // Position of the child buffer where it appears first in the master.
364         DocIterator firstChildPosition(Buffer const * child);
365
366         /** \returns true only when the file is fully loaded.
367          *  Used to prevent the premature generation of previews
368          *  and by the citation inset.
369          */
370         bool isFullyLoaded() const;
371         /// Set by buffer_funcs' newFile.
372         void setFullyLoaded(bool);
373
374         /// Our main text (inside the top InsetText)
375         Text & text() const;
376
377         /// Our top InsetText
378         Inset & inset() const;
379
380         //
381         // Macro handling
382         //
383         /// Collect macro definitions in paragraphs
384         void updateMacros() const;
385         /// Iterate through the whole buffer and try to resolve macros
386         void updateMacroInstances() const;
387
388         /// List macro names of this buffer, the parent and the children
389         void listMacroNames(MacroNameSet & macros) const;
390         /// Collect macros of the parent and its children in front of this buffer.
391         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
392
393         /// Return macro defined before pos (or in the master buffer)
394         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
395         /// Return macro defined anywhere in the buffer (or in the master buffer)
396         MacroData const * getMacro(docstring const & name, bool global = true) const;
397         /// Return macro defined before the inclusion of the child
398         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
399
400         /// Replace the inset contents for insets which InsetCode is equal
401         /// to the passed \p inset_code.
402         void changeRefsIfUnique(docstring const & from, docstring const & to,
403                 InsetCode code);
404
405         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
406         /// including preamble
407         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
408                 bool full_source) const;
409
410         /// Access to error list.
411         /// This method is used only for GUI visualisation of Buffer related
412         /// errors (like parsing or LateX compilation). This method is const
413         /// because modifying the returned ErrorList does not touch the document
414         /// contents.
415         ErrorList & errorList(std::string const & type) const;
416
417         /// The Toc backend.
418         /// This is useful only for screen visualisation of the Buffer. This
419         /// method is const because modifying this backend does not touch
420         /// the document contents.
421         TocBackend & tocBackend() const;
422
423         ///
424         Undo & undo();
425
426         /// This function is called when the buffer is changed.
427         void changed() const;
428         ///
429         void updateTocItem(std::string const &, DocIterator const &) const;
430         /// This function is called when the buffer structure is changed.
431         void structureChanged() const;
432         /// This function is called when some parsing error shows up.
433         void errors(std::string const & err) const;
434         /// This function is called when the buffer busy status change.
435         void setBusy(bool on) const;
436         /// This function is called when the buffer readonly status change.
437         void setReadOnly(bool on) const;
438         /// Update window titles of all users.
439         void updateTitles() const;
440         /// Reset autosave timers for all users.
441         void resetAutosaveTimers() const;
442         ///
443         void message(docstring const & msg) const;
444
445         ///
446         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
447         ///
448         bool Buffer::hasGuiDelegate() const;
449
450         ///
451         void autoSave() const;
452
453         /// return the format of the buffer on a string
454         std::string bufferFormat() const;
455
456         ///
457         bool doExport(std::string const & format, bool put_in_tempdir,
458                 std::string & result_file) const;
459         ///
460         bool doExport(std::string const & format, bool put_in_tempdir) const;
461         ///
462         bool preview(std::string const & format) const;
463         ///
464         bool isExportable(std::string const & format) const;
465         ///
466         std::vector<Format const *> exportableFormats(bool only_viewable) const;
467
468         ///
469         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
470         References & references(docstring const & label);
471         References const & references(docstring const & label) const;
472         void clearReferenceCache() const;
473         void setInsetLabel(docstring const & label, InsetLabel const * il);
474         InsetLabel const * insetLabel(docstring const & label) const;
475
476         // FIXME: buf should should be const because updateLabels() modifies
477         // the contents of the paragraphs.
478         void updateLabels(bool childonly = false) const;
479         ///
480         void updateLabels(ParIterator & parit) const;
481
482 private:
483         /// search for macro in local (buffer) table or in children
484         MacroData const * getBufferMacro(docstring const & name,
485                                          DocIterator const & pos) const;
486         /** Update macro table starting with position of it
487             \param it in some text inset
488         */
489         void updateMacros(DocIterator & it,
490                                      DocIterator & scope) const;
491
492         ///
493         void collectRelatives(BufferSet & bufs) const;
494
495         ///
496         bool readFileHelper(support::FileName const & s);
497         ///
498         std::vector<std::string> backends() const;
499         /** Inserts a file into a document
500             \return \c false if method fails.
501         */
502         ReadStatus readFile(Lexer &, support::FileName const & filename,
503                             bool fromString = false);
504
505         /// Use the Pimpl idiom to hide the internals.
506         class Impl;
507         /// The pointer never changes although *pimpl_'s contents may.
508         Impl * const d;
509
510         frontend::GuiBufferDelegate * gui_;
511
512         /// This function is called when the buffer structure is changed.
513         Signal structureChanged_;
514         /// This function is called when some parsing error shows up.
515         //Signal errors(std::string const &) = 0;
516         /// This function is called when some message shows up.
517         //Signal message(docstring const &) = 0;
518         /// This function is called when the buffer busy status change.
519         //Signal setBusy(bool) = 0;
520         /// Reset autosave timers for all users.
521         Signal resetAutosaveTimers_;
522 };
523
524
525 } // namespace lyx
526
527 #endif