OpenTTD Source 20250521-master-g82876c25e0
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"
17
18#include "safeguards.h"
19
24{
25 /* We are pressing TAB for the first time after reset. */
26 if (this->suggestions.empty()) {
27 this->InitSuggestions(this->textbuf->GetText());
28 if (this->suggestions.empty()) {
29 return false;
30 }
31 this->ApplySuggestion(prefix, suggestions[0]);
32 return true;
33 }
34
35 /* We are pressing TAB again on the same text. */
36 if (this->current_suggestion_index + 1 < this->suggestions.size()) {
37 this->ApplySuggestion(prefix, this->suggestions[++this->current_suggestion_index]);
38 } else {
39 /* We are out of options, restore original text. */
40 this->textbuf->Assign(initial_buf);
41 this->Reset();
42 }
43 return true;
44}
45
46void AutoCompletion::Reset()
47{
48 this->prefix = "";
49 this->query = "";
50 this->initial_buf.clear();
51 this->suggestions.clear();
52 this->current_suggestion_index = 0;
53}
54
55void AutoCompletion::InitSuggestions(std::string_view text)
56{
57 this->initial_buf = text;
58 size_t space_pos = this->initial_buf.find_last_of(' ');
59 this->query = this->initial_buf;
60 if (space_pos == std::string::npos) {
61 this->prefix = "";
62 } else {
63 this->prefix = this->query.substr(0, space_pos + 1);
64 this->query.remove_prefix(space_pos + 1);
65 }
66
67 this->suggestions = this->GetSuggestions(prefix, query);
68 this->current_suggestion_index = 0;
69}
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.
std::string_view GetText() const
Get the current text.
Definition textbuf.cpp:284
void Assign(std::string_view text)
Copy a string into the textbuffer.
Definition textbuf.cpp:420
Base of the town class.