How far away are dreams of the perfect “file search”

Do you often run a search on text files? I have been every day for more than 25 years.


My tasks are very different in complexity and scope.


First of all, as a programmer, I, of course, need searches in codes. These tasks are simple (sets of folders and files are small) and fast (results appear almost immediately).


Secondly, as an operator, I have to search through hundreds (sometimes thousands) of folders among thousands (sometimes hundreds of thousands) of files. These are difficult tasks both in terms of results and the time they are received. Usually the results of such searches still require further manual or software processing.


All work happens in Windows.


I will tell you where I was led by the desire to have a suitable tool for such tasks.


In the beginning was TextPad


For over 10 years, TextPad has been my primary lightweight tool.
Then (before and after 2000), he did an excellent job.


File search looked like this ( TextPad , 2004)


TextPad_fif


Impressions

(+) В диалоге мало настроек, поэтому он не заслоняет содержимое файлов.
(+) Вкладка с результатами поиска имеет спец.поведение — Ввод/ДвКлик позволяют открыть найденный фрагмент. В остальном это обычный текст "в памяти" редактора.
(+) Есть настройка File counts only для поиска не самих фрагментов, а только их количества по файлам. Это заметно ускоряет предварительный поиск.
(-) В диалоге мало настроек и мало команд. Окно диалога фиксированного размера.
(-) Вычурный язык регулярных выражений, например, вместо принятого сейчас \w нужно было писать [:word:].
В целом тут качественно, но скромно.




Reels and comparisons


The limitations of the TextPad and its freezing led to constant sampling by other editors.
Now I do not remember all tried, but among them were:


  • MS Visual Studio . Heavy Monster.
  • The Eclipse . Also a monster.
  • IntelliJ IDEA . Charming. Served and serves as a supplier of examples of how to make it convenient .


    Impressions

    Тот старый IDEA уже утерян. Для сравнения текущая реализация в PyCharm, 2017.1.3
    PyCharm_fif
    (+) Невообразимое число настроек и режимов.
    (+) Самодостаточность диалога: видны и результаты, и исходные тексты, и статистика поиска.
    (-) Нет ограничения на глубину поиска по папкам — либо одна, либо сразу все.
    (-) Нет (не знаю способа) поиска по нескольким папкам.
    (-) Нет (не знаю способа) вывода результатов в текстовом формате.


    В целом это мощно, но не универсально.




  • Notepad ++ . I do not remember what prevented him from switching.
  • SublimeText3 , 2013. Hacking tools - great work, a minimum of money, but it takes a lot to keep in mind .


    Impressions

    Sublime_fif
    (+) Минимум контролов.
    (-) Разные настройки "где искать" все в одном поле. Нужно учитывать их взаимодействие.
    (-) Только прикрепленный диалог.
    (+) Результаты сразу попадают в текстовую вкладку, и они наглядные.
    (-) Результаты фиксированного формата: полный путь и имя файла, потом найденные в нем строки. От локализации найденных фрагментов есть только номера строк.
    (+) Есть настройка "Контекст", чтобы в Результаты попадали найденные строки вместе с соседями.






There is such a guy


Taking the principle of "No perfect tool? Create", changed the direction of effort.
Began to pay attention to the responsiveness of developers. And in 2012 I was lucky with SynWrite .


The only developer, Alexey Torgashin, accepted most of the ideas, did it quickly and efficiently. Typical implementation time is a day or two. At the forum I asked him about the finishing touches, then about one more, then about ten more, and another ... Somewhere in the top ten, I realized that we had a good meeting .


From my submission, Alexey brought the file search to this state ( SynWrite , 2016)


image


Impressions

(+) Есть извлечение папки из текущего файла Current folder.
(+) Можно сортировать файлы по дате модификации.
(+) Есть список готовых наборов для поиска preset и быстрый доступ к ним (F3).
(-) Диалог очень перегружен и занимает много места.
(-) Результаты оформлены в виде контрола дерево в нижней панели. Чтобы получить их в текстовом виде нужно вызывать команду из локального меню.




"What do you want, older?"


With SynWrite, search has become much easier. As you know, the appetite comes with eating, so my Wishlist all multiplied. That's just the attitude towards them from the developer, my golden fish , was all the more critical - "The black blue sea" .


That's what I wanted to get


  1. Be sure to need the results immediately in text form (for further processing).
  2. Results must be self-sufficient! So that they can be saved, closed, opened - and they remained fresh , that is, ready to work.
  3. Need to search the files on the disk and in the open (modified) files.
  4. Dialogue when solving simple problems should be compact. In particular, controls for "replacements" and rare settings should not interfere with a normal search.
  5. Be sure to need the option for results along with adjacent lines .
  6. You need the mode "full description of one result in one line" (for further processing).
  7. Background information on how to fill in the fields is needed not in an external file or a cloud page, but right there, for example, in tooltips.



Do it yourself!


I was lucky again. Alexey created the new CudaText editor and screwed the Python API to it .


Finally, you could do everything as you want in the form of a plug-in on Python.


The first version was released in May 2016.


Minimum set of controls

fif-dlg-min


Maximum set of controls

fif-full-dlg
Это, конечно, не совсем первый блин, но желание "все запихать в пирогдиалог" явно просматривается.


Here is what I apply now.


cuda_fif


Implemented all Wishlist from the list of "What you need."


(1) The results can be seen either within the dialogue, or immediately output to a file (if [x] Send).


(2) The results are self-descriptive. In the text


fif_rpt_info


enough information to find out the full file name and location of the found fragment.
1:21:6means: 1 line, 21 columns, fragment length 6.


Plugin can extract and use this information.


(3) There is a search for unsaved documents. For this purpose, a In folderspecial line is entered in the field <Open Files>(abbreviations <Tabs>and work <t>).


(4) In the dialog, you can hide the controls needed to specify the excluded files, to perform replacements, to display the results and source codes.


Hidden controls

• Минимальный набор fif_min
• Минимальный набор и замены fif_repl
• Минимальный набор и задание исключений для файлов fif_excl


(7) In tooltips, signatures to freely filled fields have explanations.


Tips

fif_incl
fif_tip_fold
Более подробная информация доступна при вызове Alt+H
fif_help_tips


Implemented many more different pieces .


  • The detour depth can be zero ( Only), full ( +All), or from 1 ( +1 level) to 5 ( +5 levels) levels.


  • Rarely used search options appear by For search



fif_extra_fi


Additional search options
• Можно пропускать поиск в *скрытых* и/или *двоичных* файлах.
• Можно предварительно отсортировать файлы по дате.
• Можно остановить поиск после нахождения заданного числа фрагментов и/или файлов.
![fif_first](https://user-images.githubusercontent.com/7419630/42456464-b0448f20-839d-11e8-8876-435fdfead1ad.png)
• Можно указать кодировки, которые будут применяться при попытках прочитать файлы (до первой успешной).

  • If the results will not appear inside the dialog ( [x] Send), then there are additional parameters for them

fif_extra_rp


Additional parameters of results
`Report to` - выводить в новый таб, в последний использованный таб, в файл с конкретным именем и открыть его.
• `Append` - дополнять предыдущие результаты.
• `Tree type` - можно по разному разбивать строки 
`<path><file><r:c:l><line>`, то есть `<путь><файл><место><строка с фрагментом>`
в частности, вообще не разбивать ("Чего тебе"-6). Возможные варианты описаны в Справке
![fif_help_tree](https://user-images.githubusercontent.com/7419630/42456892-a7d867c0-839e-11e8-87f2-2b9ce6b5c530.png)
• `Align (r:c:l)` - дополнять пробелами данные из `<r:c:l>` так, чтобы все `<строки с фрагментом>` начинались с общей колонки.
Пример: ![fif_align](https://user-images.githubusercontent.com/7419630/42616450-036e3ae6-85b7-11e8-861a-cf27a3a07c7a.png)
• `Add context` - дополнять результаты соседними строками ("Чего тебе"-5).

  • You can memorize the search parameters - make presets . The first five presets are applied by Ctrl+1(.. 5), the rest are from a menu or dialog.Presets


    Presets dialog

    fif_pset




  • You can memorize the place / size of the dialogue / controls - do Layout. The first five layouts are applied by Alt+1(.. 5), the rest are from the menu.


  • Almost everything in the dialogue can be done without a mouse . For this there is


    Hotkeys

    fif_help_keys




  • For teams there is


    Menu

    Кнопка с гамбургером — это просто "=" с подчеркиванием, поэтому она доступна по Alt+=.
    fif_menu_find




  • The search process is divided into three successive phases:
    • a collection of suitable files is formed,
    • fragments are extracted from files,
    • a report is filled in with results.
    Information about each phase and their change is displayed in the status control.
    Escallows you to interrupt only the current phase and move on to the next with already accumulated data.


  • In addition to the usual user-defined parameters, there are many rarely changed options. Now there are 19 of them and for them a separate dialogue


    Options dialog

    fif_opts
    Например, среди опций есть такие:
    • Использовать выделенный текст для заполнения поля Find what при открытии диалога.
    • Прерывать одним ESC все фазы поиска.
    • Закрывать диалог при удачном поиске и выводе результатов в файл.
    • Сворачивать предыдущие результаты при дописывании новых в тот же файл.
    • Сохранять все параметры поиска в первой строке результатов. Это позволяет позже загрузить их в диалог.
    • Пропускать файлы с размером больше заданного.
    • Задать стиль для найденных фрагментов. Доступны цвет/жирность/наклонность текста, цвет фона, стиль рамки с каждой стороны. На снимках выше установлен стиль "рамка точками под фрагментом".




  • Some teams of the plugin work before and after the dialogue.

cuda_menu


From the main menu CudaText
`Find in *` - вызывать диалог с готовыми параметрами для разных поисков.
• `Navigate to *` - прыжки из результатов в исходники, с разными размещениями места, где открыть исходник.
• `Jump to *` - прыжки к следующему/предыдущему фрагменту этого же исходника, к фрагменту в следующем исходнике, к фрагменту в следующей папке.
• `Configure *` - какой прыжок делать при двойном клике в результатах, разные прыжки при разных зажатых модификаторах
![fif_dclk](https://user-images.githubusercontent.com/7419630/42460070-aa1c5f26-83a5-11e8-9103-11f676dcf08a.png)



CudaText and Python


A few words about the platform on which my plugin has grown.


Alexey Torgashin made SynWrite at Delphi. Half of the codes of this editor were licensed from another developer, and this prevented the introduction of new ideas. And Delphi paid. Because of this, Alexey switched to Free Pascal and IDE Lazarus , implemented the missing parts on his own and created CudaText in 2015 , and SynWrite froze. The opportunity to start from scratch was used sensibly - he made some strong design improvements.


  1. Settings began to be superimposed by layers: default , general , lex , current file . They began to be stored in json, not in ini. Changing the settings has become the usual text editing format json.
  2. The kernel got rid of a huge number of non-critical services. In particular, from searching files, macros, calling external utilities, menu configurators, snippets, sorts, favorites, etc.
  3. To create such services, the kernel provides the Python API, which includes a GUI library. Now all previous services have been implemented with plugins and a lot of new ones have been added.
  4. In addition, the core itself has become multi-modular. There are components of markers, bookmarks, attributes for brackets, etc.

Here you can clearly see the influence of Sublime Text . As far as I know, Alexey does not hide that he takes into account ideas from Sublime and its plug-ins. At Atom and Brackets, he also glances.


It turned out in itself is good, but taking into account Alexey’s high productivity and responsiveness, it’s excellent. To clarify what kind of productivity and responsiveness we are talking about, here are some facts:


  • Alexey created: lexers - 201, linters - 34, snippet-sets - 12, plug-ins - 93.
  • Since October 2015, there have been more than 1,200 wishes (no complaints) on the GitHub , of which more than 90% are satisfied.

CudaText is free, open source, there are builds for Win / Linux / Mac / BSD. I myself use only the Win-version, but I see suggestions and complaints from users with Linux and Mac. On the same Lazarus written, by the way, Total Commander .


It is interesting to compare Python API with Sublime and with CudaText . They are completely different.


• For Sublime, an object style of type DOM.


• With CudaText, a procedural style of the OS API type, for example, WIN32.


Apparently this difference comes from implementation languages. If the editor itself is implemented on Python, then the DOM API style is natural for it - you can store references to objects. And if the editor is in Pascal, then he can only store handlers.


• Sublime API has no GUI. The plugin can apparently use the Python GUI (Tk? WxPython? Qt?), But the style will contrast with Sublime.


• CudaText provides for GUI plug-ins in the general style of the application. Firstly, there is a large arsenal of basic controls: checklistbox, listview, checklistview, treeview. And of course, the usual buttons, checks, single- and multi-line editor, combo box, etc. Secondly, there is the ability to embed CudaText components of the GUI. In the snapshots above, these are status controls, local menus, and editor controls with results / sources. Such a complementarity with a clean Python GUI is impossible to achieve.


And without GUI live

Поскольку я уже создал десяток плагинов для CudaText, и большинство из них общались с пользователем с помощью диалоговых окон, мне теперь крайне сложно представить, как можно создавать плагины без этого богатства. Конечно, если у плагина только один диалог, который позволяет задавать настройки, то редактирование json дает адекватную замену. Но такое редактирование выполняется "до запуска" плагина, оно не может помочь, если нужна живая runtime реакция пользователя.




Is there a limit?


About once every two or three months, and it’s been, I remind, for two and a half years, it seems to me that “this is the final” - the dialogue has been licked out, the results are shown by all means, there are all useful commands. But since this tool is constantly in operation, since almost all of its features are applied, so long as the hands click on another search or study the next results, the head is looking for new improvements. And finds!


There are new ideas

Например, за время написания этого поста родились такие:
• Можно выделить текст в контролах Результаты или Исходник и дать команду на его поиск.
• Можно перехватывать события "открыт файл" с результатами и восстанавливать стиль найденных фрагментов.


In addition, it is interesting for me to understand - can the collective mind suggest new moves in this game . Therefore, I conclude with a question to fellow programmers:
What else can you add to the "file search" inside a text editor?




Technical details of the implementation of the plug-in to CudaText

• Язык: Python 3.5
• GUI библиотека: CudaText API
• Разработчики: Андрей Квичанский
• Объем кода: >300 Кб
• Число ToDo для плагина: >250
• Число bug/wish для CudaText API: >150
• Форум плагина: GitHub issues


How to try

• Скачать сборку CudaText под свою ОС, распаковать или установить.
• Запустить CudaText и вызвать команду меню Plugins/Addons Manager/Install...
• Ввести "find", чтобы фильтр оставиль только FindInFile, установить (может быть потребуется перевызов CudaText, на Win не нужно).
• Вызвать команду меню Plugins/Find in Files/Find in files...


Also popular now: