2 * \file frontend_helpers.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "frontend_helpers.h"
17 #include "BufferParams.h"
21 #include "LyXLength.h"
23 #include <boost/regex.hpp>
30 #include "frontends/FileDialog.h"
31 #include "frontends/Alert.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/Package.h"
35 #include "support/filetools.h"
36 #include "support/lstrings.h"
37 #include "support/lyxalgo.h"
38 #include "support/os.h"
39 #include "support/Package.h"
40 #include "support/Path.h"
41 #include "support/Systemcall.h"
43 #include <boost/cregex.hpp>
52 using support::ascii_lowercase;
53 using support::bformat;
54 using support::compare_ascii_no_case;
55 using support::contains;
56 using support::getVectorFromString;
58 using support::prefixIs;
69 vector<string> const init_possible_cite_commands()
71 char const * const pos[] = {
73 "citet", "citep", "citealt", "citealp",
74 "citeauthor", "citeyear", "citeyearpar",
75 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
76 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
77 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
79 "footcite", "footcitet", "footcitep", "footcitealt",
80 "footcitealp", "footciteauthor", "footciteyear",
86 size_t const size_pos = sizeof(pos) / sizeof(pos[0]);
88 return vector<string>(pos, pos + size_pos);
92 vector<string> const & possible_cite_commands()
94 static vector<string> const pos = init_possible_cite_commands();
99 bool is_possible_cite_command(string const & input)
101 vector<string> const & possibles = possible_cite_commands();
102 vector<string>::const_iterator const end = possibles.end();
103 return std::find(possibles.begin(), end, input) != end;
107 string const default_cite_command(CiteEngine engine)
114 case ENGINE_NATBIB_AUTHORYEAR:
117 case ENGINE_NATBIB_NUMERICAL:
128 static const docstring TheBibliographyRef(from_ascii("TheBibliographyRef"));
133 string const asValidLatexCommand(string const & input,
134 CiteEngine const engine)
136 string const default_str = default_cite_command(engine);
137 if (!is_possible_cite_command(input))
143 output = default_str;
146 case ENGINE_NATBIB_AUTHORYEAR:
147 case ENGINE_NATBIB_NUMERICAL:
148 if (input == "cite" || input == "citefield" ||
149 input == "citetitle" || input == "cite*")
150 output = default_str;
151 else if (prefixIs(input, "foot"))
152 output = input.substr(4);
157 case ENGINE_JURABIB: {
158 // Jurabib does not support the 'uppercase' natbib style.
160 output = string(1, 'c') + input.substr(1);
164 // Jurabib does not support the 'full' natbib style.
165 string::size_type const n = output.size() - 1;
166 if (output != "cite*" && output[n] == '*')
167 output = output.substr(0, n);
177 docstring const familyName(docstring const & name)
179 // Very simple parser
180 docstring fname = name;
182 // possible authorname combinations are:
183 // "Surname, FirstName"
185 // "FirstName Surname"
187 docstring::size_type idx = fname.find(',');
188 if (idx != docstring::npos)
189 return ltrim(fname.substr(0, idx));
190 idx = fname.rfind('.');
191 if (idx != docstring::npos)
192 fname = ltrim(fname.substr(idx + 1));
193 // test if we have a LaTeX Space in front
194 if (fname[0] == '\\')
195 return fname.substr(2);
201 docstring const getAbbreviatedAuthor(InfoMap const & map, string const & key)
203 BOOST_ASSERT(!map.empty());
205 InfoMap::const_iterator it = map.find(key);
208 docstring const & data = it->second;
210 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
211 docstring::size_type const pos = data.find(TheBibliographyRef);
212 if (pos != docstring::npos) {
217 docstring const opt = trim(data.substr(0, pos - 1));
222 split(opt, authors, '(');
226 docstring author = parseBibTeX(data, "author");
229 author = parseBibTeX(data, "editor");
231 if (author.empty()) {
232 author = parseBibTeX(data, "key");
235 return from_utf8(key);
239 vector<docstring> const authors = getVectorFromString(author, from_ascii(" and "));
243 if (authors.size() == 2)
244 return bformat(_("%1$s and %2$s"),
245 familyName(authors[0]), familyName(authors[1]));
247 if (authors.size() > 2)
248 return bformat(_("%1$s et al."), familyName(authors[0]));
250 return familyName(authors[0]);
254 docstring const getYear(InfoMap const & map, string const & key)
256 BOOST_ASSERT(!map.empty());
258 InfoMap::const_iterator it = map.find(key);
261 docstring const & data = it->second;
263 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
264 docstring::size_type const pos = data.find(TheBibliographyRef);
265 if (pos != docstring::npos) {
270 docstring const opt =
271 trim(data.substr(0, pos - 1));
276 docstring const tmp = split(opt, authors, '(');
278 split(tmp, year, ')');
283 docstring year = parseBibTeX(data, "year");
293 // A functor for use with std::sort, leading to case insensitive sorting
294 class compareNoCase: public std::binary_function<string, string, bool>
297 bool operator()(string const & s1, string const & s2) const {
298 return compare_ascii_no_case(s1, s2) < 0;
305 vector<string> const getKeys(InfoMap const & map)
307 vector<string> bibkeys;
308 InfoMap::const_iterator it = map.begin();
309 InfoMap::const_iterator end = map.end();
310 for (; it != end; ++it) {
311 bibkeys.push_back(it->first);
314 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
319 docstring const getInfo(InfoMap const & map, string const & key)
321 BOOST_ASSERT(!map.empty());
323 InfoMap::const_iterator it = map.find(key);
326 docstring const & data = it->second;
328 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
329 docstring::size_type const pos = data.find(TheBibliographyRef);
330 if (pos != docstring::npos) {
331 docstring::size_type const pos2 = pos + TheBibliographyRef.size();
332 docstring const info = trim(data.substr(pos2));
336 // Search for all possible "required" keys
337 docstring author = parseBibTeX(data, "author");
339 author = parseBibTeX(data, "editor");
341 docstring year = parseBibTeX(data, "year");
342 docstring title = parseBibTeX(data, "title");
343 docstring booktitle = parseBibTeX(data, "booktitle");
344 docstring chapter = parseBibTeX(data, "chapter");
345 docstring number = parseBibTeX(data, "number");
346 docstring volume = parseBibTeX(data, "volume");
347 docstring pages = parseBibTeX(data, "pages");
348 docstring annote = parseBibTeX(data, "annote");
349 docstring media = parseBibTeX(data, "journal");
351 media = parseBibTeX(data, "publisher");
353 media = parseBibTeX(data, "school");
355 media = parseBibTeX(data, "institution");
357 odocstringstream result;
359 result << author << ", ";
362 if (!booktitle.empty())
363 result << ", in " << booktitle;
364 if (!chapter.empty())
365 result << ", Ch. " << chapter;
367 result << ", " << media;
369 result << ", vol. " << volume;
371 result << ", no. " << number;
373 result << ", pp. " << pages;
375 result << ", " << year;
377 result << "\n\n" << annote;
379 docstring const result_str = rtrim(result.str());
380 if (!result_str.empty())
383 // This should never happen (or at least be very unusual!)
390 // Escape special chars.
391 // All characters are literals except: '.|*?+(){}[]^$\'
392 // These characters are literals when preceded by a "\", which is done here
393 // @todo: This function should be moved to support, and then the test in tests
394 // should be moved there as well.
395 string const escape_special_chars(string const & expr)
397 // Search for all chars '.|*?+(){}[^$]\'
398 // Note that '[' and '\' must be escaped.
399 // This is a limitation of boost::regex, but all other chars in BREs
400 // are assumed literal.
401 boost::regex reg("[].|*?+(){}^$\\[\\\\]");
403 // $& is a perl-like expression that expands to all
404 // of the current match
405 // The '$' must be prefixed with the escape character '\' for
406 // boost to treat it as a literal.
407 // Thus, to prefix a matched expression with '\', we use:
408 return boost::regex_replace(expr, reg, "\\\\$&");
412 // A functor for use with std::find_if, used to ascertain whether a
413 // data entry matches the required regex_
414 // @throws: boost::regex_error if the supplied regex pattern is not valid
415 // @todo: This function should be moved to support.
416 class RegexMatch : public std::unary_function<string, bool>
419 // re and icase are used to construct an instance of boost::RegEx.
420 // if icase is true, then matching is insensitive to case
421 RegexMatch(InfoMap const & m, string const & re, bool icase)
422 : map_(m), regex_(re, icase) {}
424 bool operator()(string const & key) const {
425 // the data searched is the key + its associated BibTeX/biblio
428 InfoMap::const_iterator info = map_.find(key);
429 if (info != map_.end())
431 data += ' ' + to_utf8(info->second);
433 // Attempts to find a match for the current RE
434 // somewhere in data.
435 return boost::regex_search(data, regex_);
439 mutable boost::regex regex_;
445 vector<string>::const_iterator
446 searchKeys(InfoMap const & theMap,
447 vector<string> const & keys,
448 string const & search_expr,
449 vector<string>::const_iterator start,
454 // Preliminary checks
455 if (start < keys.begin() || start >= keys.end())
458 string expr = trim(search_expr);
463 // We must escape special chars in the search_expr so that
464 // it is treated as a simple string by boost::regex.
465 expr = escape_special_chars(expr);
468 // Build the functor that will be passed to find_if.
469 RegexMatch const match(theMap, expr, !caseSensitive);
471 // Search the vector of 'keys' from 'start' for one
472 // that matches the predicate 'match'. Searching can
473 // be forward or backward from start.
475 return std::find_if(start, keys.end(), match);
477 vector<string>::const_reverse_iterator rit(start);
478 vector<string>::const_reverse_iterator rend = keys.rend();
479 rit = std::find_if(rit, rend, match);
483 // This is correct and always safe.
484 // (See Meyer's Effective STL, Item 28.)
485 return (++rit).base();
487 catch (boost::regex_error &) {
493 docstring const parseBibTeX(docstring data, string const & findkey)
495 // at first we delete all characters right of '%' and
496 // replace tabs through a space and remove leading spaces
497 // we read the data line by line so that the \n are
501 docstring dummy = token(data,'\n', Entries);
502 while (!dummy.empty()) {
504 dummy = subst(dummy, '\t', ' ');
506 dummy = ltrim(dummy);
507 // ignore lines with a beginning '%' or ignore all right of %
508 docstring::size_type const idx =
509 dummy.empty() ? docstring::npos : dummy.find('%');
510 if (idx != docstring::npos)
511 // Check if this is really a comment or just "\%"
512 if (idx == 0 || dummy[idx - 1] != '\\')
513 dummy.erase(idx, docstring::npos);
515 // This is "\%", so just erase the '\'
516 dummy.erase(idx - 1, 1);
517 // do we have a new token or a new line of
518 // the same one? In the first case we ignore
519 // the \n and in the second we replace it
521 if (!dummy.empty()) {
522 if (!contains(dummy, '='))
523 data_ += ' ' + dummy;
527 dummy = token(data, '\n', ++Entries);
530 // replace double commas with "" for easy scanning
531 data = subst(data_, from_ascii(",,"), from_ascii("\"\""));
537 // now get only the important line of the bibtex entry.
538 // all entries are devided by ',' except the last one.
540 // now we have same behaviour for all entries because the last one
544 // parsing of title and booktitle is different from the
545 // others, because booktitle contains title
547 dummy = token(data, ',', Entries++);
548 if (!dummy.empty()) {
549 found = contains(ascii_lowercase(dummy), from_ascii(findkey));
550 if (findkey == "title" &&
551 contains(ascii_lowercase(dummy), from_ascii("booktitle")))
554 } while (!found && !dummy.empty());
559 // we are not sure, if we get all, because "key= "blah, blah" is
561 // Therefore we read all until the next "=" character, which follows a
563 docstring keyvalue = dummy;
564 dummy = token(data, ',', Entries++);
565 while (!contains(dummy, '=') && !dummy.empty()) {
566 keyvalue += ',' + dummy;
567 dummy = token(data, ',', Entries++);
570 // replace double "" with originals ,, (two commas)
571 // leaving us with the all-important line
572 data = subst(keyvalue, from_ascii("\"\""), from_ascii(",,"));
577 // 2. if there is no opening '{' then a closing '{' is probably cruft.
578 if (!contains(data, '{'))
579 data = rtrim(data, "}");
580 // happens, when last keyword
581 docstring::size_type const idx =
582 !data.empty() ? data.find('=') : docstring::npos;
584 if (idx == docstring::npos)
587 data = trim(data.substr(idx));
590 if (data.length() < 2 || data[0] != '=')
593 // delete '=' and the following spaces
594 data = ltrim(data, " =");
595 if (data.length() < 2) {
596 // not long enough to find delimiters
599 docstring::size_type keypos = 1;
601 if (data[0] == '{') {
603 } else if (data[0] == '"') {
606 // no {} and no "", pure data but with a
607 // possible ',' at the end
608 return rtrim(data, ",");
610 docstring tmp = data.substr(keypos);
611 while (tmp.find('{') != docstring::npos &&
612 tmp.find('}') != docstring::npos &&
613 tmp.find('{') < tmp.find('}') &&
614 tmp.find('{') < tmp.find(enclosing)) {
616 keypos += tmp.find('{') + 1;
617 tmp = data.substr(keypos);
618 keypos += tmp.find('}') + 1;
619 tmp = data.substr(keypos);
621 if (tmp.find(enclosing) == docstring::npos)
624 keypos += tmp.find(enclosing);
625 return data.substr(1, keypos - 1);
635 char const * const citeCommands[] = {
636 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
637 "citeyear", "citeyearpar" };
639 unsigned int const nCiteCommands =
640 sizeof(citeCommands) / sizeof(char *);
642 CiteStyle const citeStyles[] = {
643 CITE, CITET, CITEP, CITEALT, CITEALP,
644 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
646 unsigned int const nCiteStyles =
647 sizeof(citeStyles) / sizeof(CiteStyle);
649 CiteStyle const citeStylesFull[] = {
650 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
652 unsigned int const nCiteStylesFull =
653 sizeof(citeStylesFull) / sizeof(CiteStyle);
655 CiteStyle const citeStylesUCase[] = {
656 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
658 unsigned int const nCiteStylesUCase =
659 sizeof(citeStylesUCase) / sizeof(CiteStyle);
664 CitationStyle::CitationStyle(string const & command)
665 : style(CITE), full(false), forceUCase(false)
670 string cmd = command;
676 string::size_type const n = cmd.size() - 1;
677 if (cmd != "cite" && cmd[n] == '*') {
679 cmd = cmd.substr(0,n);
682 char const * const * const last = citeCommands + nCiteCommands;
683 char const * const * const ptr = std::find(citeCommands, last, cmd);
686 size_t idx = ptr - citeCommands;
687 style = citeStyles[idx];
692 string const CitationStyle::asLatexStr() const
694 string cite = citeCommands[style];
696 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
697 if (std::find(citeStylesFull, last, style) != last)
702 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
703 if (std::find(citeStylesUCase, last, style) != last)
711 vector<CiteStyle> const getCiteStyles(CiteEngine const engine)
713 unsigned int nStyles = 0;
714 unsigned int start = 0;
721 case ENGINE_NATBIB_AUTHORYEAR:
722 case ENGINE_NATBIB_NUMERICAL:
723 nStyles = nCiteStyles - 1;
727 nStyles = nCiteStyles;
732 typedef vector<CiteStyle> cite_vec;
734 cite_vec styles(nStyles);
735 cite_vec::size_type i = 0;
737 for (; i != styles.size(); ++i, ++j)
738 styles[i] = citeStyles[j];
744 vector<docstring> const
745 getNumericalStrings(string const & key,
746 InfoMap const & map, vector<CiteStyle> const & styles)
749 return vector<docstring>();
751 docstring const author = getAbbreviatedAuthor(map, key);
752 docstring const year = getYear(map, key);
753 if (author.empty() || year.empty())
754 return vector<docstring>();
756 vector<docstring> vec(styles.size());
757 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
763 str = from_ascii("[#ID]");
767 str = author + " [#ID]";
771 str = author + " #ID";
775 str = from_ascii("#ID");
787 str = '(' + year + ')';
798 vector<docstring> const
799 getAuthorYearStrings(string const & key,
800 InfoMap const & map, vector<CiteStyle> const & styles)
803 return vector<docstring>();
805 docstring const author = getAbbreviatedAuthor(map, key);
806 docstring const year = getYear(map, key);
807 if (author.empty() || year.empty())
808 return vector<docstring>();
810 vector<docstring> vec(styles.size());
811 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
816 // jurabib only: Author/Annotator
817 // (i.e. the "before" field, 2nd opt arg)
818 str = author + "/<" + _("before") + '>';
822 str = author + " (" + year + ')';
826 str = '(' + author + ", " + year + ')';
830 str = author + ' ' + year ;
834 str = author + ", " + year ;
846 str = '(' + year + ')';
856 } // namespace biblio
860 vector<FamilyPair> const getFamilyData()
862 vector<FamilyPair> family(5);
866 pr.first = _("No change");
867 pr.second = LyXFont::IGNORE_FAMILY;
870 pr.first = _("Roman");
871 pr.second = LyXFont::ROMAN_FAMILY;
874 pr.first = _("Sans Serif");
875 pr.second = LyXFont::SANS_FAMILY;
878 pr.first = _("Typewriter");
879 pr.second = LyXFont::TYPEWRITER_FAMILY;
882 pr.first = _("Reset");
883 pr.second = LyXFont::INHERIT_FAMILY;
890 vector<SeriesPair> const getSeriesData()
892 vector<SeriesPair> series(4);
896 pr.first = _("No change");
897 pr.second = LyXFont::IGNORE_SERIES;
900 pr.first = _("Medium");
901 pr.second = LyXFont::MEDIUM_SERIES;
904 pr.first = _("Bold");
905 pr.second = LyXFont::BOLD_SERIES;
908 pr.first = _("Reset");
909 pr.second = LyXFont::INHERIT_SERIES;
916 vector<ShapePair> const getShapeData()
918 vector<ShapePair> shape(6);
922 pr.first = _("No change");
923 pr.second = LyXFont::IGNORE_SHAPE;
926 pr.first = _("Upright");
927 pr.second = LyXFont::UP_SHAPE;
930 pr.first = _("Italic");
931 pr.second = LyXFont::ITALIC_SHAPE;
934 pr.first = _("Slanted");
935 pr.second = LyXFont::SLANTED_SHAPE;
938 pr.first = _("Small Caps");
939 pr.second = LyXFont::SMALLCAPS_SHAPE;
942 pr.first = _("Reset");
943 pr.second = LyXFont::INHERIT_SHAPE;
950 vector<SizePair> const getSizeData()
952 vector<SizePair> size(14);
956 pr.first = _("No change");
957 pr.second = LyXFont::IGNORE_SIZE;
960 pr.first = _("Tiny");
961 pr.second = LyXFont::SIZE_TINY;
964 pr.first = _("Smallest");
965 pr.second = LyXFont::SIZE_SCRIPT;
968 pr.first = _("Smaller");
969 pr.second = LyXFont::SIZE_FOOTNOTE;
972 pr.first = _("Small");
973 pr.second = LyXFont::SIZE_SMALL;
976 pr.first = _("Normal");
977 pr.second = LyXFont::SIZE_NORMAL;
980 pr.first = _("Large");
981 pr.second = LyXFont::SIZE_LARGE;
984 pr.first = _("Larger");
985 pr.second = LyXFont::SIZE_LARGER;
988 pr.first = _("Largest");
989 pr.second = LyXFont::SIZE_LARGEST;
992 pr.first = _("Huge");
993 pr.second = LyXFont::SIZE_HUGE;
996 pr.first = _("Huger");
997 pr.second = LyXFont::SIZE_HUGER;
1000 pr.first = _("Increase");
1001 pr.second = LyXFont::INCREASE_SIZE;
1004 pr.first = _("Decrease");
1005 pr.second = LyXFont::DECREASE_SIZE;
1008 pr.first = _("Reset");
1009 pr.second = LyXFont::INHERIT_SIZE;
1016 vector<BarPair> const getBarData()
1018 vector<BarPair> bar(5);
1022 pr.first = _("No change");
1026 pr.first = _("Emph");
1027 pr.second = EMPH_TOGGLE;
1030 pr.first = _("Underbar");
1031 pr.second = UNDERBAR_TOGGLE;
1034 pr.first = _("Noun");
1035 pr.second = NOUN_TOGGLE;
1038 pr.first = _("Reset");
1039 pr.second = INHERIT;
1046 vector<ColorPair> const getColorData()
1048 vector<ColorPair> color(11);
1052 pr.first = _("No change");
1053 pr.second = LColor::ignore;
1056 pr.first = _("No color");
1057 pr.second = LColor::none;
1060 pr.first = _("Black");
1061 pr.second = LColor::black;
1064 pr.first = _("White");
1065 pr.second = LColor::white;
1068 pr.first = _("Red");
1069 pr.second = LColor::red;
1072 pr.first = _("Green");
1073 pr.second = LColor::green;
1076 pr.first = _("Blue");
1077 pr.second = LColor::blue;
1080 pr.first = _("Cyan");
1081 pr.second = LColor::cyan;
1084 pr.first = _("Magenta");
1085 pr.second = LColor::magenta;
1088 pr.first = _("Yellow");
1089 pr.second = LColor::yellow;
1092 pr.first = _("Reset");
1093 pr.second = LColor::inherit;
1104 : public std::binary_function<LanguagePair,
1108 bool operator()(LanguagePair const & lhs,
1109 LanguagePair const & rhs) const {
1110 return lhs.first < rhs.first;
1117 vector<LanguagePair> const getLanguageData(bool character_dlg)
1119 vector<LanguagePair>::size_type const size = character_dlg ?
1120 languages.size() + 2 : languages.size();
1122 vector<LanguagePair> langs(size);
1124 if (character_dlg) {
1125 langs[0].first = _("No change");
1126 langs[0].second = "ignore";
1127 langs[1].first = _("Reset");
1128 langs[1].second = "reset";
1131 vector<string>::size_type i = character_dlg ? 2 : 0;
1132 for (Languages::const_iterator cit = languages.begin();
1133 cit != languages.end(); ++cit) {
1134 langs[i].first = _(cit->second.display());
1135 langs[i].second = cit->second.lang();
1139 // Don't sort "ignore" and "reset"
1140 vector<LanguagePair>::iterator begin = character_dlg ?
1141 langs.begin() + 2 : langs.begin();
1143 std::sort(begin, langs.end(), Sorter());
1148 } // namespace frontend
1150 using support::addName;
1151 using support::FileFilterList;
1152 using support::getExtension;
1153 using support::libFileSearch;
1154 using support::makeAbsPath;
1155 using support::makeRelPath;
1156 using support::onlyFilename;
1157 using support::onlyPath;
1158 using support::package;
1159 using support::prefixIs;
1160 using support::removeExtension;
1162 namespace frontend {
1165 docstring const browseFile(docstring const & filename,
1166 docstring const & title,
1167 FileFilterList const & filters,
1169 pair<docstring,docstring> const & dir1,
1170 pair<docstring,docstring> const & dir2)
1172 docstring lastPath = from_ascii(".");
1173 if (!filename.empty())
1174 lastPath = from_utf8(onlyPath(to_utf8(filename)));
1176 FileDialog fileDlg(title, LFUN_SELECT_FILE_SYNC, dir1, dir2);
1178 FileDialog::Result result;
1181 result = fileDlg.save(lastPath, filters,
1182 from_utf8(onlyFilename(to_utf8(filename))));
1184 result = fileDlg.open(lastPath, filters,
1185 from_utf8(onlyFilename(to_utf8(filename))));
1187 return result.second;
1191 docstring const browseRelFile(docstring const & filename,
1192 docstring const & refpath,
1193 docstring const & title,
1194 FileFilterList const & filters,
1196 pair<docstring,docstring> const & dir1,
1197 pair<docstring,docstring> const & dir2)
1199 docstring const fname = from_utf8(makeAbsPath(
1200 to_utf8(filename), to_utf8(refpath)).absFilename());
1202 docstring const outname = browseFile(fname, title, filters, save,
1204 docstring const reloutname = makeRelPath(outname, refpath);
1205 if (prefixIs(reloutname, from_ascii("../")))
1213 docstring const browseLibFile(docstring const & dir,
1214 docstring const & name,
1215 docstring const & ext,
1216 docstring const & title,
1217 FileFilterList const & filters)
1220 pair<docstring, docstring> const dir1(_("System files|#S#s"),
1221 from_utf8(addName(package().system_support().absFilename(), to_utf8(dir))));
1223 pair<docstring, docstring> const dir2(_("User files|#U#u"),
1224 from_utf8(addName(package().user_support().absFilename(), to_utf8(dir))));
1226 docstring const result = browseFile(from_utf8(
1227 libFileSearch(to_utf8(dir), to_utf8(name), to_utf8(ext)).absFilename()),
1228 title, filters, false, dir1, dir2);
1230 // remove the extension if it is the default one
1231 docstring noextresult;
1232 if (from_utf8(getExtension(to_utf8(result))) == ext)
1233 noextresult = from_utf8(removeExtension(to_utf8(result)));
1235 noextresult = result;
1237 // remove the directory, if it is the default one
1238 docstring const file = from_utf8(onlyFilename(to_utf8(noextresult)));
1239 if (from_utf8(libFileSearch(to_utf8(dir), to_utf8(file), to_utf8(ext)).absFilename()) == result)
1246 docstring const browseDir(docstring const & pathname,
1247 docstring const & title,
1248 pair<docstring,docstring> const & dir1,
1249 pair<docstring,docstring> const & dir2)
1251 docstring lastPath = from_ascii(".");
1252 if (!pathname.empty())
1253 lastPath = from_utf8(onlyPath(to_utf8(pathname)));
1255 FileDialog fileDlg(title, LFUN_SELECT_FILE_SYNC, dir1, dir2);
1257 FileDialog::Result const result =
1258 fileDlg.opendir(lastPath, from_utf8(onlyFilename(to_utf8(pathname))));
1260 return result.second;
1264 vector<docstring> const getLatexUnits()
1266 vector<docstring> units;
1268 char const * str = stringFromUnit(i);
1269 for (; str != 0; ++i, str = stringFromUnit(i))
1270 units.push_back(from_ascii(str));
1275 } // namespace frontend
1278 using support::bformat;
1279 using support::contains;
1280 using support::FileName;
1281 using support::getExtension;
1282 using support::getFileContents;
1283 using support::getVectorFromString;
1284 using support::libFileSearch;
1285 using support::onlyFilename;
1286 using support::package;
1287 using support::quoteName;
1288 using support::split;
1289 using support::Systemcall;
1290 using support::token;
1292 namespace frontend {
1294 void rescanTexStyles()
1296 // Run rescan in user lyx directory
1297 support::Path p(package().user_support());
1298 FileName const command = libFileSearch("scripts", "TeXFiles.py");
1300 int const status = one.startscript(Systemcall::Wait,
1301 lyx::support::os::python() + ' ' +
1302 quoteName(command.toFilesystemEncoding()));
1306 Alert::error(_("Could not update TeX information"),
1307 bformat(_("The script `%s' failed."), lyx::from_utf8(command.absFilename())));
1313 // Run texhash in user lyx directory
1314 support::Path p(package().user_support());
1316 //path to texhash through system
1318 one.startscript(Systemcall::Wait,"texhash");
1322 void getTexFileList(string const & filename, std::vector<string> & list)
1325 FileName const file = libFileSearch("", filename);
1329 list = getVectorFromString(getFileContents(file), "\n");
1331 // Normalise paths like /foo//bar ==> /foo/bar
1332 boost::RegEx regex("/{2,}");
1333 std::vector<string>::iterator it = list.begin();
1334 std::vector<string>::iterator end = list.end();
1335 for (; it != end; ++it) {
1336 *it = regex.Merge((*it), "/");
1339 // remove empty items and duplicates
1340 list.erase(std::remove(list.begin(), list.end(), ""), list.end());
1341 eliminate_duplicates(list);
1345 string const getListOfOptions(string const & classname, string const & type)
1347 FileName const filename(getTexFileFromList(classname, type));
1348 if (filename.empty())
1350 string optionList = string();
1351 std::ifstream is(filename.toFilesystemEncoding().c_str());
1355 if (contains(s,"DeclareOption")) {
1356 s = s.substr(s.find("DeclareOption"));
1357 s = split(s,'{'); // cut front
1358 s = token(s,'}',0); // cut end
1359 optionList += (s + '\n');
1366 string const getTexFileFromList(string const & file,
1367 string const & type)
1369 string file_ = file;
1370 // do we need to add the suffix?
1371 if (!(getExtension(file) == type))
1372 file_ += '.' + type;
1374 lyxerr << "Searching for file " << file_ << endl;
1378 lstfile = "clsFiles.lst";
1379 else if (type == "sty")
1380 lstfile = "styFiles.lst";
1381 else if (type == "bst")
1382 lstfile = "bstFiles.lst";
1383 else if (type == "bib")
1384 lstfile = "bibFiles.lst";
1385 FileName const abslstfile = libFileSearch(string(), lstfile);
1386 if (abslstfile.empty()) {
1387 lyxerr << "File `'" << lstfile << "' not found." << endl;
1390 string const allClasses = getFileContents(abslstfile);
1392 string classfile = token(allClasses, '\n', entries);
1394 while ((!contains(classfile, file) ||
1395 (onlyFilename(classfile) != file)) &&
1397 classfile = token(allClasses, '\n', ++entries);
1400 // now we have filename with full path
1401 lyxerr << "with full path: " << classfile << endl;
1406 } // namespace frontend