OpenTTD Source  20241121-master-g67a0fccfad
autocompletion.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 
12 #include "autocompletion.h"
13 
14 #include "console_internal.h"
15 #include "town.h"
16 #include "network/network_base.h"
17 
18 #include "safeguards.h"
19 
20 bool AutoCompletion::AutoComplete()
21 {
22  // We are pressing TAB for the first time after reset.
23  if (this->suggestions.empty()) {
24  this->InitSuggestions(this->textbuf->buf);
25  if (this->suggestions.empty()) {
26  return false;
27  }
28  this->ApplySuggestion(prefix, suggestions[0]);
29  return true;
30  }
31 
32  // We are pressing TAB again on the same text.
33  if (this->current_suggestion_index + 1 < this->suggestions.size()) {
34  this->ApplySuggestion(prefix, this->suggestions[++this->current_suggestion_index]);
35  } else {
36  // We are out of options, restore original text.
37  this->textbuf->Assign(initial_buf);
38  this->Reset();
39  }
40  return true;
41 }
42 
43 void AutoCompletion::Reset()
44 {
45  this->prefix = "";
46  this->query = "";
47  this->initial_buf.clear();
48  this->suggestions.clear();
49  this->current_suggestion_index = 0;
50 }
51 
52 void AutoCompletion::InitSuggestions(std::string_view text)
53 {
54  this->initial_buf = text;
55  size_t space_pos = this->initial_buf.find_last_of(' ');
56  this->query = this->initial_buf;
57  if (space_pos == std::string::npos) {
58  this->prefix = "";
59  } else {
60  this->prefix = this->query.substr(0, space_pos + 1);
61  this->query.remove_prefix(space_pos + 1);
62  }
63 
64  this->suggestions = this->GetSuggestions(prefix, query);
65  this->current_suggestion_index = 0;
66 }
Generic auto-completion engine.
std::string_view query
Last token of the text. This is used to based the suggestions on.
std::string_view prefix
Prefix of the text before the last space.
std::string initial_buf
Value of text buffer when we started current suggestion session.
Internally used functions for the console.
Base core network types and some helper functions to access them.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
void Assign(StringID string)
Render a string into the textbuffer.
Definition: textbuf.cpp:431
char *const buf
buffer in which text is saved
Definition: textbuf_type.h:32
Base of the town class.