You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1836 lines
56 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. # This file is part of ranger, the console file manager.
  3. # This configuration file is licensed under the same terms as ranger.
  4. # ===================================================================
  5. #
  6. # NOTE: If you copied this file to /etc/ranger/commands_full.py or
  7. # ~/.config/ranger/commands_full.py, then it will NOT be loaded by ranger,
  8. # and only serve as a reference.
  9. #
  10. # ===================================================================
  11. # This file contains ranger's commands.
  12. # It's all in python; lines beginning with # are comments.
  13. #
  14. # Note that additional commands are automatically generated from the methods
  15. # of the class ranger.core.actions.Actions.
  16. #
  17. # You can customize commands in the files /etc/ranger/commands.py (system-wide)
  18. # and ~/.config/ranger/commands.py (per user).
  19. # They have the same syntax as this file. In fact, you can just copy this
  20. # file to ~/.config/ranger/commands_full.py with
  21. # `ranger --copy-config=commands_full' and make your modifications, don't
  22. # forget to rename it to commands.py. You can also use
  23. # `ranger --copy-config=commands' to copy a short sample commands.py that
  24. # has everything you need to get started.
  25. # But make sure you update your configs when you update ranger.
  26. #
  27. # ===================================================================
  28. # Every class defined here which is a subclass of `Command' will be used as a
  29. # command in ranger. Several methods are defined to interface with ranger:
  30. # execute(): called when the command is executed.
  31. # cancel(): called when closing the console.
  32. # tab(tabnum): called when <TAB> is pressed.
  33. # quick(): called after each keypress.
  34. #
  35. # tab() argument tabnum is 1 for <TAB> and -1 for <S-TAB> by default
  36. #
  37. # The return values for tab() can be either:
  38. # None: There is no tab completion
  39. # A string: Change the console to this string
  40. # A list/tuple/generator: cycle through every item in it
  41. #
  42. # The return value for quick() can be:
  43. # False: Nothing happens
  44. # True: Execute the command afterwards
  45. #
  46. # The return value for execute() and cancel() doesn't matter.
  47. #
  48. # ===================================================================
  49. # Commands have certain attributes and methods that facilitate parsing of
  50. # the arguments:
  51. #
  52. # self.line: The whole line that was written in the console.
  53. # self.args: A list of all (space-separated) arguments to the command.
  54. # self.quantifier: If this command was mapped to the key "X" and
  55. # the user pressed 6X, self.quantifier will be 6.
  56. # self.arg(n): The n-th argument, or an empty string if it doesn't exist.
  57. # self.rest(n): The n-th argument plus everything that followed. For example,
  58. # if the command was "search foo bar a b c", rest(2) will be "bar a b c"
  59. # self.start(n): Anything before the n-th argument. For example, if the
  60. # command was "search foo bar a b c", start(2) will be "search foo"
  61. #
  62. # ===================================================================
  63. # And this is a little reference for common ranger functions and objects:
  64. #
  65. # self.fm: A reference to the "fm" object which contains most information
  66. # about ranger.
  67. # self.fm.notify(string): Print the given string on the screen.
  68. # self.fm.notify(string, bad=True): Print the given string in RED.
  69. # self.fm.reload_cwd(): Reload the current working directory.
  70. # self.fm.thisdir: The current working directory. (A File object.)
  71. # self.fm.thisfile: The current file. (A File object too.)
  72. # self.fm.thistab.get_selection(): A list of all selected files.
  73. # self.fm.execute_console(string): Execute the string as a ranger command.
  74. # self.fm.open_console(string): Open the console with the given string
  75. # already typed in for you.
  76. # self.fm.move(direction): Moves the cursor in the given direction, which
  77. # can be something like down=3, up=5, right=1, left=1, to=6, ...
  78. #
  79. # File objects (for example self.fm.thisfile) have these useful attributes and
  80. # methods:
  81. #
  82. # tfile.path: The path to the file.
  83. # tfile.basename: The base name only.
  84. # tfile.load_content(): Force a loading of the directories content (which
  85. # obviously works with directories only)
  86. # tfile.is_directory: True/False depending on whether it's a directory.
  87. #
  88. # For advanced commands it is unavoidable to dive a bit into the source code
  89. # of ranger.
  90. # ===================================================================
  91. from __future__ import (absolute_import, division, print_function)
  92. from collections import deque
  93. import os
  94. import re
  95. from ranger.api.commands import Command
  96. class alias(Command):
  97. """:alias <newcommand> <oldcommand>
  98. Copies the oldcommand as newcommand.
  99. """
  100. context = 'browser'
  101. resolve_macros = False
  102. def execute(self):
  103. if not self.arg(1) or not self.arg(2):
  104. self.fm.notify('Syntax: alias <newcommand> <oldcommand>', bad=True)
  105. return
  106. self.fm.commands.alias(self.arg(1), self.rest(2))
  107. class echo(Command):
  108. """:echo <text>
  109. Display the text in the statusbar.
  110. """
  111. def execute(self):
  112. self.fm.notify(self.rest(1))
  113. class cd(Command):
  114. """:cd [-r] <path>
  115. The cd command changes the directory.
  116. If the path is a file, selects that file.
  117. The command 'cd -' is equivalent to typing ``.
  118. Using the option "-r" will get you to the real path.
  119. """
  120. def execute(self):
  121. if self.arg(1) == '-r':
  122. self.shift()
  123. destination = os.path.realpath(self.rest(1))
  124. if os.path.isfile(destination):
  125. self.fm.select_file(destination)
  126. return
  127. else:
  128. destination = self.rest(1)
  129. if not destination:
  130. destination = '~'
  131. if destination == '-':
  132. self.fm.enter_bookmark('`')
  133. else:
  134. self.fm.cd(destination)
  135. def _tab_args(self):
  136. # dest must be rest because path could contain spaces
  137. if self.arg(1) == '-r':
  138. start = self.start(2)
  139. dest = self.rest(2)
  140. else:
  141. start = self.start(1)
  142. dest = self.rest(1)
  143. if dest:
  144. head, tail = os.path.split(os.path.expanduser(dest))
  145. if head:
  146. dest_exp = os.path.join(os.path.normpath(head), tail)
  147. else:
  148. dest_exp = tail
  149. else:
  150. dest_exp = ''
  151. return (start, dest_exp, os.path.join(self.fm.thisdir.path, dest_exp),
  152. dest.endswith(os.path.sep))
  153. @staticmethod
  154. def _tab_paths(dest, dest_abs, ends_with_sep):
  155. if not dest:
  156. try:
  157. return next(os.walk(dest_abs))[1], dest_abs
  158. except (OSError, StopIteration):
  159. return [], ''
  160. if ends_with_sep:
  161. try:
  162. return [os.path.join(dest, path) for path in next(os.walk(dest_abs))[1]], ''
  163. except (OSError, StopIteration):
  164. return [], ''
  165. return None, None
  166. def _tab_match(self, path_user, path_file):
  167. if self.fm.settings.cd_tab_case == 'insensitive':
  168. path_user = path_user.lower()
  169. path_file = path_file.lower()
  170. elif self.fm.settings.cd_tab_case == 'smart' and path_user.islower():
  171. path_file = path_file.lower()
  172. return path_file.startswith(path_user)
  173. def _tab_normal(self, dest, dest_abs):
  174. dest_dir = os.path.dirname(dest)
  175. dest_base = os.path.basename(dest)
  176. try:
  177. dirnames = next(os.walk(os.path.dirname(dest_abs)))[1]
  178. except (OSError, StopIteration):
  179. return [], ''
  180. return [os.path.join(dest_dir, d) for d in dirnames if self._tab_match(dest_base, d)], ''
  181. def _tab_fuzzy_match(self, basepath, tokens):
  182. """ Find directories matching tokens recursively """
  183. if not tokens:
  184. tokens = ['']
  185. paths = [basepath]
  186. while True:
  187. token = tokens.pop()
  188. matches = []
  189. for path in paths:
  190. try:
  191. directories = next(os.walk(path))[1]
  192. except (OSError, StopIteration):
  193. continue
  194. matches += [os.path.join(path, d) for d in directories
  195. if self._tab_match(token, d)]
  196. if not tokens or not matches:
  197. return matches
  198. paths = matches
  199. return None
  200. def _tab_fuzzy(self, dest, dest_abs):
  201. tokens = []
  202. basepath = dest_abs
  203. while True:
  204. basepath_old = basepath
  205. basepath, token = os.path.split(basepath)
  206. if basepath == basepath_old:
  207. break
  208. if os.path.isdir(basepath_old) and not token.startswith('.'):
  209. basepath = basepath_old
  210. break
  211. tokens.append(token)
  212. paths = self._tab_fuzzy_match(basepath, tokens)
  213. if not os.path.isabs(dest):
  214. paths_rel = basepath
  215. paths = [os.path.relpath(path, paths_rel) for path in paths]
  216. else:
  217. paths_rel = ''
  218. return paths, paths_rel
  219. def tab(self, tabnum):
  220. from os.path import sep
  221. start, dest, dest_abs, ends_with_sep = self._tab_args()
  222. paths, paths_rel = self._tab_paths(dest, dest_abs, ends_with_sep)
  223. if paths is None:
  224. if self.fm.settings.cd_tab_fuzzy:
  225. paths, paths_rel = self._tab_fuzzy(dest, dest_abs)
  226. else:
  227. paths, paths_rel = self._tab_normal(dest, dest_abs)
  228. paths.sort()
  229. if self.fm.settings.cd_bookmarks:
  230. paths[0:0] = [
  231. os.path.relpath(v.path, paths_rel) if paths_rel else v.path
  232. for v in self.fm.bookmarks.dct.values() for path in paths
  233. if v.path.startswith(os.path.join(paths_rel, path) + sep)
  234. ]
  235. if not paths:
  236. return None
  237. if len(paths) == 1:
  238. return start + paths[0] + sep
  239. return [start + dirname for dirname in paths]
  240. class chain(Command):
  241. """:chain <command1>; <command2>; ...
  242. Calls multiple commands at once, separated by semicolons.
  243. """
  244. def execute(self):
  245. if not self.rest(1).strip():
  246. self.fm.notify('Syntax: chain <command1>; <command2>; ...', bad=True)
  247. return
  248. for command in [s.strip() for s in self.rest(1).split(";")]:
  249. self.fm.execute_console(command)
  250. class shell(Command):
  251. escape_macros_for_shell = True
  252. def execute(self):
  253. if self.arg(1) and self.arg(1)[0] == '-':
  254. flags = self.arg(1)[1:]
  255. command = self.rest(2)
  256. else:
  257. flags = ''
  258. command = self.rest(1)
  259. if command:
  260. self.fm.execute_command(command, flags=flags)
  261. def tab(self, tabnum):
  262. from ranger.ext.get_executables import get_executables
  263. if self.arg(1) and self.arg(1)[0] == '-':
  264. command = self.rest(2)
  265. else:
  266. command = self.rest(1)
  267. start = self.line[0:len(self.line) - len(command)]
  268. try:
  269. position_of_last_space = command.rindex(" ")
  270. except ValueError:
  271. return (start + program + ' ' for program
  272. in get_executables() if program.startswith(command))
  273. if position_of_last_space == len(command) - 1:
  274. selection = self.fm.thistab.get_selection()
  275. if len(selection) == 1:
  276. return self.line + selection[0].shell_escaped_basename + ' '
  277. return self.line + '%s '
  278. before_word, start_of_word = self.line.rsplit(' ', 1)
  279. return (before_word + ' ' + file.shell_escaped_basename
  280. for file in self.fm.thisdir.files or []
  281. if file.shell_escaped_basename.startswith(start_of_word))
  282. class open_with(Command):
  283. def execute(self):
  284. app, flags, mode = self._get_app_flags_mode(self.rest(1))
  285. self.fm.execute_file(
  286. files=[f for f in self.fm.thistab.get_selection()],
  287. app=app,
  288. flags=flags,
  289. mode=mode)
  290. def tab(self, tabnum):
  291. return self._tab_through_executables()
  292. def _get_app_flags_mode(self, string): # pylint: disable=too-many-branches,too-many-statements
  293. """Extracts the application, flags and mode from a string.
  294. examples:
  295. "mplayer f 1" => ("mplayer", "f", 1)
  296. "atool 4" => ("atool", "", 4)
  297. "p" => ("", "p", 0)
  298. "" => None
  299. """
  300. app = ''
  301. flags = ''
  302. mode = 0
  303. split = string.split()
  304. if len(split) == 1:
  305. part = split[0]
  306. if self._is_app(part):
  307. app = part
  308. elif self._is_flags(part):
  309. flags = part
  310. elif self._is_mode(part):
  311. mode = part
  312. elif len(split) == 2:
  313. part0 = split[0]
  314. part1 = split[1]
  315. if self._is_app(part0):
  316. app = part0
  317. if self._is_flags(part1):
  318. flags = part1
  319. elif self._is_mode(part1):
  320. mode = part1
  321. elif self._is_flags(part0):
  322. flags = part0
  323. if self._is_mode(part1):
  324. mode = part1
  325. elif self._is_mode(part0):
  326. mode = part0
  327. if self._is_flags(part1):
  328. flags = part1
  329. elif len(split) >= 3:
  330. part0 = split[0]
  331. part1 = split[1]
  332. part2 = split[2]
  333. if self._is_app(part0):
  334. app = part0
  335. if self._is_flags(part1):
  336. flags = part1
  337. if self._is_mode(part2):
  338. mode = part2
  339. elif self._is_mode(part1):
  340. mode = part1
  341. if self._is_flags(part2):
  342. flags = part2
  343. elif self._is_flags(part0):
  344. flags = part0
  345. if self._is_mode(part1):
  346. mode = part1
  347. elif self._is_mode(part0):
  348. mode = part0
  349. if self._is_flags(part1):
  350. flags = part1
  351. return app, flags, int(mode)
  352. def _is_app(self, arg):
  353. return not self._is_flags(arg) and not arg.isdigit()
  354. @staticmethod
  355. def _is_flags(arg):
  356. from ranger.core.runner import ALLOWED_FLAGS
  357. return all(x in ALLOWED_FLAGS for x in arg)
  358. @staticmethod
  359. def _is_mode(arg):
  360. return all(x in '0123456789' for x in arg)
  361. class set_(Command):
  362. """:set <option name>=<python expression>
  363. Gives an option a new value.
  364. Use `:set <option>!` to toggle or cycle it, e.g. `:set flush_input!`
  365. """
  366. name = 'set' # don't override the builtin set class
  367. def execute(self):
  368. name = self.arg(1)
  369. name, value, _, toggle = self.parse_setting_line_v2()
  370. if toggle:
  371. self.fm.toggle_option(name)
  372. else:
  373. self.fm.set_option_from_string(name, value)
  374. def tab(self, tabnum): # pylint: disable=too-many-return-statements
  375. from ranger.gui.colorscheme import get_all_colorschemes
  376. name, value, name_done = self.parse_setting_line()
  377. settings = self.fm.settings
  378. if not name:
  379. return sorted(self.firstpart + setting for setting in settings)
  380. if not value and not name_done:
  381. return sorted(self.firstpart + setting for setting in settings
  382. if setting.startswith(name))
  383. if not value:
  384. value_completers = {
  385. "colorscheme":
  386. # Cycle through colorschemes when name, but no value is specified
  387. lambda: sorted(self.firstpart + colorscheme for colorscheme
  388. in get_all_colorschemes(self.fm)),
  389. "column_ratios":
  390. lambda: self.firstpart + ",".join(map(str, settings[name])),
  391. }
  392. def default_value_completer():
  393. return self.firstpart + str(settings[name])
  394. return value_completers.get(name, default_value_completer)()
  395. if bool in settings.types_of(name):
  396. if 'true'.startswith(value.lower()):
  397. return self.firstpart + 'True'
  398. if 'false'.startswith(value.lower()):
  399. return self.firstpart + 'False'
  400. # Tab complete colorscheme values if incomplete value is present
  401. if name == "colorscheme":
  402. return sorted(self.firstpart + colorscheme for colorscheme
  403. in get_all_colorschemes(self.fm) if colorscheme.startswith(value))
  404. return None
  405. class setlocal(set_):
  406. """:setlocal path=<regular expression> <option name>=<python expression>
  407. Gives an option a new value.
  408. """
  409. PATH_RE_DQUOTED = re.compile(r'^setlocal\s+path="(.*?)"')
  410. PATH_RE_SQUOTED = re.compile(r"^setlocal\s+path='(.*?)'")
  411. PATH_RE_UNQUOTED = re.compile(r'^path=(.*?)$')
  412. def _re_shift(self, match):
  413. if not match:
  414. return None
  415. path = os.path.expanduser(match.group(1))
  416. for _ in range(len(path.split())):
  417. self.shift()
  418. return path
  419. def execute(self):
  420. path = self._re_shift(self.PATH_RE_DQUOTED.match(self.line))
  421. if path is None:
  422. path = self._re_shift(self.PATH_RE_SQUOTED.match(self.line))
  423. if path is None:
  424. path = self._re_shift(self.PATH_RE_UNQUOTED.match(self.arg(1)))
  425. if path is None and self.fm.thisdir:
  426. path = self.fm.thisdir.path
  427. if not path:
  428. return
  429. name, value, _ = self.parse_setting_line()
  430. self.fm.set_option_from_string(name, value, localpath=path)
  431. class setintag(set_):
  432. """:setintag <tag or tags> <option name>=<option value>
  433. Sets an option for directories that are tagged with a specific tag.
  434. """
  435. def execute(self):
  436. tags = self.arg(1)
  437. self.shift()
  438. name, value, _ = self.parse_setting_line()
  439. self.fm.set_option_from_string(name, value, tags=tags)
  440. class default_linemode(Command):
  441. def execute(self):
  442. from ranger.container.fsobject import FileSystemObject
  443. if len(self.args) < 2:
  444. self.fm.notify(
  445. "Usage: default_linemode [path=<regexp> | tag=<tag(s)>] <linemode>", bad=True)
  446. # Extract options like "path=..." or "tag=..." from the command line
  447. arg1 = self.arg(1)
  448. method = "always"
  449. argument = None
  450. if arg1.startswith("path="):
  451. method = "path"
  452. argument = re.compile(arg1[5:])
  453. self.shift()
  454. elif arg1.startswith("tag="):
  455. method = "tag"
  456. argument = arg1[4:]
  457. self.shift()
  458. # Extract and validate the line mode from the command line
  459. lmode = self.rest(1)
  460. if lmode not in FileSystemObject.linemode_dict:
  461. self.fm.notify(
  462. "Invalid linemode: %s; should be %s" % (
  463. lmode, "/".join(FileSystemObject.linemode_dict)),
  464. bad=True,
  465. )
  466. # Add the prepared entry to the fm.default_linemodes
  467. entry = [method, argument, lmode]
  468. self.fm.default_linemodes.appendleft(entry)
  469. # Redraw the columns
  470. if self.fm.ui.browser:
  471. for col in self.fm.ui.browser.columns:
  472. col.need_redraw = True
  473. def tab(self, tabnum):
  474. return (self.arg(0) + " " + lmode
  475. for lmode in self.fm.thisfile.linemode_dict.keys()
  476. if lmode.startswith(self.arg(1)))
  477. class quit(Command): # pylint: disable=redefined-builtin
  478. """:quit
  479. Closes the current tab, if there's only one tab.
  480. Otherwise quits if there are no tasks in progress.
  481. """
  482. def _exit_no_work(self):
  483. if self.fm.loader.has_work():
  484. self.fm.notify('Not quitting: Tasks in progress: Use `quit!` to force quit')
  485. else:
  486. self.fm.exit()
  487. def execute(self):
  488. if len(self.fm.tabs) >= 2:
  489. self.fm.tab_close()
  490. else:
  491. self._exit_no_work()
  492. class quit_bang(Command):
  493. """:quit!
  494. Closes the current tab, if there's only one tab.
  495. Otherwise force quits immediately.
  496. """
  497. name = 'quit!'
  498. allow_abbrev = False
  499. def execute(self):
  500. if len(self.fm.tabs) >= 2:
  501. self.fm.tab_close()
  502. else:
  503. self.fm.exit()
  504. class quitall(Command):
  505. """:quitall
  506. Quits if there are no tasks in progress.
  507. """
  508. def _exit_no_work(self):
  509. if self.fm.loader.has_work():
  510. self.fm.notify('Not quitting: Tasks in progress: Use `quitall!` to force quit')
  511. else:
  512. self.fm.exit()
  513. def execute(self):
  514. self._exit_no_work()
  515. class quitall_bang(Command):
  516. """:quitall!
  517. Force quits immediately.
  518. """
  519. name = 'quitall!'
  520. allow_abbrev = False
  521. def execute(self):
  522. self.fm.exit()
  523. class terminal(Command):
  524. """:terminal
  525. Spawns an "x-terminal-emulator" starting in the current directory.
  526. """
  527. def execute(self):
  528. from ranger.ext.get_executables import get_term
  529. self.fm.run(get_term(), flags='f')
  530. class delete(Command):
  531. """:delete
  532. Tries to delete the selection or the files passed in arguments (if any).
  533. The arguments use a shell-like escaping.
  534. "Selection" is defined as all the "marked files" (by default, you
  535. can mark files with space or v). If there are no marked files,
  536. use the "current file" (where the cursor is)
  537. When attempting to delete non-empty directories or multiple
  538. marked files, it will require a confirmation.
  539. """
  540. allow_abbrev = False
  541. escape_macros_for_shell = True
  542. def execute(self):
  543. import shlex
  544. from functools import partial
  545. def is_directory_with_files(path):
  546. return os.path.isdir(path) and not os.path.islink(path) and len(os.listdir(path)) > 0
  547. if self.rest(1):
  548. files = shlex.split(self.rest(1))
  549. many_files = (len(files) > 1 or is_directory_with_files(files[0]))
  550. else:
  551. cwd = self.fm.thisdir
  552. tfile = self.fm.thisfile
  553. if not cwd or not tfile:
  554. self.fm.notify("Error: no file selected for deletion!", bad=True)
  555. return
  556. # relative_path used for a user-friendly output in the confirmation.
  557. files = [f.relative_path for f in self.fm.thistab.get_selection()]
  558. many_files = (cwd.marked_items or is_directory_with_files(tfile.path))
  559. confirm = self.fm.settings.confirm_on_delete
  560. if confirm != 'never' and (confirm != 'multiple' or many_files):
  561. self.fm.ui.console.ask(
  562. "Confirm deletion of: %s (y/N)" % ', '.join(files),
  563. partial(self._question_callback, files),
  564. ('n', 'N', 'y', 'Y'),
  565. )
  566. else:
  567. # no need for a confirmation, just delete
  568. self.fm.delete(files)
  569. def tab(self, tabnum):
  570. return self._tab_directory_content()
  571. def _question_callback(self, files, answer):
  572. if answer == 'y' or answer == 'Y':
  573. self.fm.delete(files)
  574. class jump_non(Command):
  575. """:jump_non [-FLAGS...]
  576. Jumps to first non-directory if highlighted file is a directory and vice versa.
  577. Flags:
  578. -r Jump in reverse order
  579. -w Wrap around if reaching end of filelist
  580. """
  581. def __init__(self, *args, **kwargs):
  582. super(jump_non, self).__init__(*args, **kwargs)
  583. flags, _ = self.parse_flags()
  584. self._flag_reverse = 'r' in flags
  585. self._flag_wrap = 'w' in flags
  586. @staticmethod
  587. def _non(fobj, is_directory):
  588. return fobj.is_directory if not is_directory else not fobj.is_directory
  589. def execute(self):
  590. tfile = self.fm.thisfile
  591. passed = False
  592. found_before = None
  593. found_after = None
  594. for fobj in self.fm.thisdir.files[::-1] if self._flag_reverse else self.fm.thisdir.files:
  595. if fobj.path == tfile.path:
  596. passed = True
  597. continue
  598. if passed:
  599. if self._non(fobj, tfile.is_directory):
  600. found_after = fobj.path
  601. break
  602. elif not found_before and self._non(fobj, tfile.is_directory):
  603. found_before = fobj.path
  604. if found_after:
  605. self.fm.select_file(found_after)
  606. elif self._flag_wrap and found_before:
  607. self.fm.select_file(found_before)
  608. class mark_tag(Command):
  609. """:mark_tag [<tags>]
  610. Mark all tags that are tagged with either of the given tags.
  611. When leaving out the tag argument, all tagged files are marked.
  612. """
  613. do_mark = True
  614. def execute(self):
  615. cwd = self.fm.thisdir
  616. tags = self.rest(1).replace(" ", "")
  617. if not self.fm.tags or not cwd.files:
  618. return
  619. for fileobj in cwd.files:
  620. try:
  621. tag = self.fm.tags.tags[fileobj.realpath]
  622. except KeyError:
  623. continue
  624. if not tags or tag in tags:
  625. cwd.mark_item(fileobj, val=self.do_mark)
  626. self.fm.ui.status.need_redraw = True
  627. self.fm.ui.need_redraw = True
  628. class console(Command):
  629. """:console <command>
  630. Open the console with the given command.
  631. """
  632. def execute(self):
  633. position = None
  634. if self.arg(1)[0:2] == '-p':
  635. try:
  636. position = int(self.arg(1)[2:])
  637. except ValueError:
  638. pass
  639. else:
  640. self.shift()
  641. self.fm.open_console(self.rest(1), position=position)
  642. class load_copy_buffer(Command):
  643. """:load_copy_buffer
  644. Load the copy buffer from datadir/copy_buffer
  645. """
  646. copy_buffer_filename = 'copy_buffer'
  647. def execute(self):
  648. import sys
  649. from ranger.container.file import File
  650. from os.path import exists
  651. fname = self.fm.datapath(self.copy_buffer_filename)
  652. unreadable = IOError if sys.version_info[0] < 3 else OSError
  653. try:
  654. fobj = open(fname, 'r')
  655. except unreadable:
  656. return self.fm.notify(
  657. "Cannot open %s" % (fname or self.copy_buffer_filename), bad=True)
  658. self.fm.copy_buffer = set(File(g)
  659. for g in fobj.read().split("\n") if exists(g))
  660. fobj.close()
  661. self.fm.ui.redraw_main_column()
  662. return None
  663. class save_copy_buffer(Command):
  664. """:save_copy_buffer
  665. Save the copy buffer to datadir/copy_buffer
  666. """
  667. copy_buffer_filename = 'copy_buffer'
  668. def execute(self):
  669. import sys
  670. fname = None
  671. fname = self.fm.datapath(self.copy_buffer_filename)
  672. unwritable = IOError if sys.version_info[0] < 3 else OSError
  673. try:
  674. fobj = open(fname, 'w')
  675. except unwritable:
  676. return self.fm.notify("Cannot open %s" %
  677. (fname or self.copy_buffer_filename), bad=True)
  678. fobj.write("\n".join(fobj.path for fobj in self.fm.copy_buffer))
  679. fobj.close()
  680. return None
  681. class unmark_tag(mark_tag):
  682. """:unmark_tag [<tags>]
  683. Unmark all tags that are tagged with either of the given tags.
  684. When leaving out the tag argument, all tagged files are unmarked.
  685. """
  686. do_mark = False
  687. class mkdir(Command):
  688. """:mkdir <dirname>
  689. Creates a directory with the name <dirname>.
  690. """
  691. def execute(self):
  692. from os.path import join, expanduser, lexists
  693. from os import makedirs
  694. dirname = join(self.fm.thisdir.path, expanduser(self.rest(1)))
  695. if not lexists(dirname):
  696. makedirs(dirname)
  697. else:
  698. self.fm.notify("file/directory exists!", bad=True)
  699. def tab(self, tabnum):
  700. return self._tab_directory_content()
  701. class touch(Command):
  702. """:touch <fname>
  703. Creates a file with the name <fname>.
  704. """
  705. def execute(self):
  706. from os.path import join, expanduser, lexists
  707. fname = join(self.fm.thisdir.path, expanduser(self.rest(1)))
  708. if not lexists(fname):
  709. open(fname, 'a').close()
  710. else:
  711. self.fm.notify("file/directory exists!", bad=True)
  712. def tab(self, tabnum):
  713. return self._tab_directory_content()
  714. class edit(Command):
  715. """:edit <filename>
  716. Opens the specified file in vim
  717. """
  718. def execute(self):
  719. if not self.arg(1):
  720. self.fm.edit_file(self.fm.thisfile.path)
  721. else:
  722. self.fm.edit_file(self.rest(1))
  723. def tab(self, tabnum):
  724. return self._tab_directory_content()
  725. class eval_(Command):
  726. """:eval [-q] <python code>
  727. Evaluates the python code.
  728. `fm' is a reference to the FM instance.
  729. To display text, use the function `p'.
  730. Examples:
  731. :eval fm
  732. :eval len(fm.directories)
  733. :eval p("Hello World!")
  734. """
  735. name = 'eval'
  736. resolve_macros = False
  737. def execute(self):
  738. # The import is needed so eval() can access the ranger module
  739. import ranger # NOQA pylint: disable=unused-import,unused-variable
  740. if self.arg(1) == '-q':
  741. code = self.rest(2)
  742. quiet = True
  743. else:
  744. code = self.rest(1)
  745. quiet = False
  746. global cmd, fm, p, quantifier # pylint: disable=invalid-name,global-variable-undefined
  747. fm = self.fm
  748. cmd = self.fm.execute_console
  749. p = fm.notify
  750. quantifier = self.quantifier
  751. try:
  752. try:
  753. result = eval(code) # pylint: disable=eval-used
  754. except SyntaxError:
  755. exec(code) # pylint: disable=exec-used
  756. else:
  757. if result and not quiet:
  758. p(result)
  759. except Exception as err: # pylint: disable=broad-except
  760. fm.notify("The error `%s` was caused by evaluating the "
  761. "following code: `%s`" % (err, code), bad=True)
  762. class rename(Command):
  763. """:rename <newname>
  764. Changes the name of the currently highlighted file to <newname>
  765. """
  766. def execute(self):
  767. from ranger.container.file import File
  768. from os import access
  769. new_name = self.rest(1)
  770. if not new_name:
  771. return self.fm.notify('Syntax: rename <newname>', bad=True)
  772. if new_name == self.fm.thisfile.relative_path:
  773. return None
  774. if access(new_name, os.F_OK):
  775. return self.fm.notify("Can't rename: file already exists!", bad=True)
  776. if self.fm.rename(self.fm.thisfile, new_name):
  777. file_new = File(new_name)
  778. self.fm.bookmarks.update_path(self.fm.thisfile.path, file_new)
  779. self.fm.tags.update_path(self.fm.thisfile.path, file_new.path)
  780. self.fm.thisdir.pointed_obj = file_new
  781. self.fm.thisfile = file_new
  782. return None
  783. def tab(self, tabnum):
  784. return self._tab_directory_content()
  785. class rename_append(Command):
  786. """:rename_append [-FLAGS...]
  787. Opens the console with ":rename <current file>" with the cursor positioned
  788. before the file extension.
  789. Flags:
  790. -a Position before all extensions
  791. -r Remove everything before extensions
  792. """
  793. def __init__(self, *args, **kwargs):
  794. super(rename_append, self).__init__(*args, **kwargs)
  795. flags, _ = self.parse_flags()
  796. self._flag_ext_all = 'a' in flags
  797. self._flag_remove = 'r' in flags
  798. def execute(self):
  799. from ranger import MACRO_DELIMITER, MACRO_DELIMITER_ESC
  800. tfile = self.fm.thisfile
  801. relpath = tfile.relative_path.replace(MACRO_DELIMITER, MACRO_DELIMITER_ESC)
  802. basename = tfile.basename.replace(MACRO_DELIMITER, MACRO_DELIMITER_ESC)
  803. if basename.find('.') <= 0:
  804. self.fm.open_console('rename ' + relpath)
  805. return
  806. if self._flag_ext_all:
  807. pos_ext = re.search(r'[^.]+', basename).end(0)
  808. else:
  809. pos_ext = basename.rindex('.')
  810. pos = len(relpath) - len(basename) + pos_ext
  811. if self._flag_remove:
  812. relpath = relpath[:-len(basename)] + basename[pos_ext:]
  813. pos -= pos_ext
  814. self.fm.open_console('rename ' + relpath, position=(7 + pos))
  815. class chmod(Command):
  816. """:chmod <octal number>
  817. Sets the permissions of the selection to the octal number.
  818. The octal number is between 0 and 777. The digits specify the
  819. permissions for the user, the group and others.
  820. A 1 permits execution, a 2 permits writing, a 4 permits reading.
  821. Add those numbers to combine them. So a 7 permits everything.
  822. """
  823. def execute(self):
  824. mode_str = self.rest(1)
  825. if not mode_str:
  826. if not self.quantifier:
  827. self.fm.notify("Syntax: chmod <octal number>", bad=True)
  828. return
  829. mode_str = str(self.quantifier)
  830. try:
  831. mode = int(mode_str, 8)
  832. if mode < 0 or mode > 0o777:
  833. raise ValueError
  834. except ValueError:
  835. self.fm.notify("Need an octal number between 0 and 777!", bad=True)
  836. return
  837. for fobj in self.fm.thistab.get_selection():
  838. try:
  839. os.chmod(fobj.path, mode)
  840. except OSError as ex:
  841. self.fm.notify(ex)
  842. # reloading directory. maybe its better to reload the selected
  843. # files only.
  844. self.fm.thisdir.content_outdated = True
  845. class bulkrename(Command):
  846. """:bulkrename
  847. This command opens a list of selected files in an external editor.
  848. After you edit and save the file, it will generate a shell script
  849. which does bulk renaming according to the changes you did in the file.
  850. This shell script is opened in an editor for you to review.
  851. After you close it, it will be executed.
  852. """
  853. def execute(self): # pylint: disable=too-many-locals,too-many-statements
  854. import sys
  855. import tempfile
  856. from ranger.container.file import File
  857. from ranger.ext.shell_escape import shell_escape as esc
  858. py3 = sys.version_info[0] >= 3
  859. # Create and edit the file list
  860. filenames = [f.relative_path for f in self.fm.thistab.get_selection()]
  861. listfile = tempfile.NamedTemporaryFile(delete=False)
  862. listpath = listfile.name
  863. if py3:
  864. listfile.write("\n".join(filenames).encode("utf-8"))
  865. else:
  866. listfile.write("\n".join(filenames))
  867. listfile.close()
  868. self.fm.execute_file([File(listpath)], app='editor')
  869. listfile = open(listpath, 'r')
  870. new_filenames = listfile.read().split("\n")
  871. listfile.close()
  872. os.unlink(listpath)
  873. if all(a == b for a, b in zip(filenames, new_filenames)):
  874. self.fm.notify("No renaming to be done!")
  875. return
  876. # Generate script
  877. cmdfile = tempfile.NamedTemporaryFile()
  878. script_lines = []
  879. script_lines.append("# This file will be executed when you close the editor.\n")
  880. script_lines.append("# Please double-check everything, clear the file to abort.\n")
  881. script_lines.extend("mv -vi -- %s %s\n" % (esc(old), esc(new))
  882. for old, new in zip(filenames, new_filenames) if old != new)
  883. script_content = "".join(script_lines)
  884. if py3:
  885. cmdfile.write(script_content.encode("utf-8"))
  886. else:
  887. cmdfile.write(script_content)
  888. cmdfile.flush()
  889. # Open the script and let the user review it, then check if the script
  890. # was modified by the user
  891. self.fm.execute_file([File(cmdfile.name)], app='editor')
  892. cmdfile.seek(0)
  893. script_was_edited = (script_content != cmdfile.read())
  894. # Do the renaming
  895. self.fm.run(['/bin/sh', cmdfile.name], flags='w')
  896. cmdfile.close()
  897. # Retag the files, but only if the script wasn't changed during review,
  898. # because only then we know which are the source and destination files.
  899. if not script_was_edited:
  900. tags_changed = False
  901. for old, new in zip(filenames, new_filenames):
  902. if old != new:
  903. oldpath = self.fm.thisdir.path + '/' + old
  904. newpath = self.fm.thisdir.path + '/' + new
  905. if oldpath in self.fm.tags:
  906. old_tag = self.fm.tags.tags[oldpath]
  907. self.fm.tags.remove(oldpath)
  908. self.fm.tags.tags[newpath] = old_tag
  909. tags_changed = True
  910. if tags_changed:
  911. self.fm.tags.dump()
  912. else:
  913. fm.notify("files have not been retagged")
  914. class relink(Command):
  915. """:relink <newpath>
  916. Changes the linked path of the currently highlighted symlink to <newpath>
  917. """
  918. def execute(self):
  919. new_path = self.rest(1)
  920. tfile = self.fm.thisfile
  921. if not new_path:
  922. return self.fm.notify('Syntax: relink <newpath>', bad=True)
  923. if not tfile.is_link:
  924. return self.fm.notify('%s is not a symlink!' % tfile.relative_path, bad=True)
  925. if new_path == os.readlink(tfile.path):
  926. return None
  927. try:
  928. os.remove(tfile.path)
  929. os.symlink(new_path, tfile.path)
  930. except OSError as err:
  931. self.fm.notify(err)
  932. self.fm.reset()
  933. self.fm.thisdir.pointed_obj = tfile
  934. self.fm.thisfile = tfile
  935. return None
  936. def tab(self, tabnum):
  937. if not self.rest(1):
  938. return self.line + os.readlink(self.fm.thisfile.path)
  939. return self._tab_directory_content()
  940. class help_(Command):
  941. """:help
  942. Display ranger's manual page.
  943. """
  944. name = 'help'
  945. def execute(self):
  946. def callback(answer):
  947. if answer == "q":
  948. return
  949. elif answer == "m":
  950. self.fm.display_help()
  951. elif answer == "c":
  952. self.fm.dump_commands()
  953. elif answer == "k":
  954. self.fm.dump_keybindings()
  955. elif answer == "s":
  956. self.fm.dump_settings()
  957. self.fm.ui.console.ask(
  958. "View [m]an page, [k]ey bindings, [c]ommands or [s]ettings? (press q to abort)",
  959. callback,
  960. list("mqkcs")
  961. )
  962. class copymap(Command):
  963. """:copymap <keys> <newkeys1> [<newkeys2>...]
  964. Copies a "browser" keybinding from <keys> to <newkeys>
  965. """
  966. context = 'browser'
  967. def execute(self):
  968. if not self.arg(1) or not self.arg(2):
  969. return self.fm.notify("Not enough arguments", bad=True)
  970. for arg in self.args[2:]:
  971. self.fm.ui.keymaps.copy(self.context, self.arg(1), arg)
  972. return None
  973. class copypmap(copymap):
  974. """:copypmap <keys> <newkeys1> [<newkeys2>...]
  975. Copies a "pager" keybinding from <keys> to <newkeys>
  976. """
  977. context = 'pager'
  978. class copycmap(copymap):
  979. """:copycmap <keys> <newkeys1> [<newkeys2>...]
  980. Copies a "console" keybinding from <keys> to <newkeys>
  981. """
  982. context = 'console'
  983. class copytmap(copymap):
  984. """:copycmap <keys> <newkeys1> [<newkeys2>...]
  985. Copies a "taskview" keybinding from <keys> to <newkeys>
  986. """
  987. context = 'taskview'
  988. class unmap(Command):
  989. """:unmap <keys> [<keys2>, ...]
  990. Remove the given "browser" mappings
  991. """
  992. context = 'browser'
  993. def execute(self):
  994. for arg in self.args[1:]:
  995. self.fm.ui.keymaps.unbind(self.context, arg)
  996. class cunmap(unmap):
  997. """:cunmap <keys> [<keys2>, ...]
  998. Remove the given "console" mappings
  999. """
  1000. context = 'browser'
  1001. class punmap(unmap):
  1002. """:punmap <keys> [<keys2>, ...]
  1003. Remove the given "pager" mappings
  1004. """
  1005. context = 'pager'
  1006. class tunmap(unmap):
  1007. """:tunmap <keys> [<keys2>, ...]
  1008. Remove the given "taskview" mappings
  1009. """
  1010. context = 'taskview'
  1011. class map_(Command):
  1012. """:map <keysequence> <command>
  1013. Maps a command to a keysequence in the "browser" context.
  1014. Example:
  1015. map j move down
  1016. map J move down 10
  1017. """
  1018. name = 'map'
  1019. context = 'browser'
  1020. resolve_macros = False
  1021. def execute(self):
  1022. if not self.arg(1) or not self.arg(2):
  1023. self.fm.notify("Syntax: {0} <keysequence> <command>".format(self.get_name()), bad=True)
  1024. return
  1025. self.fm.ui.keymaps.bind(self.context, self.arg(1), self.rest(2))
  1026. class cmap(map_):
  1027. """:cmap <keysequence> <command>
  1028. Maps a command to a keysequence in the "console" context.
  1029. Example:
  1030. cmap <ESC> console_close
  1031. cmap <C-x> console_type test
  1032. """
  1033. context = 'console'
  1034. class tmap(map_):
  1035. """:tmap <keysequence> <command>
  1036. Maps a command to a keysequence in the "taskview" context.
  1037. """
  1038. context = 'taskview'
  1039. class pmap(map_):
  1040. """:pmap <keysequence> <command>
  1041. Maps a command to a keysequence in the "pager" context.
  1042. """
  1043. context = 'pager'
  1044. class scout(Command):
  1045. """:scout [-FLAGS...] <pattern>
  1046. Swiss army knife command for searching, traveling and filtering files.
  1047. Flags:
  1048. -a Automatically open a file on unambiguous match
  1049. -e Open the selected file when pressing enter
  1050. -f Filter files that match the current search pattern
  1051. -g Interpret pattern as a glob pattern
  1052. -i Ignore the letter case of the files
  1053. -k Keep the console open when changing a directory with the command
  1054. -l Letter skipping; e.g. allow "rdme" to match the file "readme"
  1055. -m Mark the matching files after pressing enter
  1056. -M Unmark the matching files after pressing enter
  1057. -p Permanent filter: hide non-matching files after pressing enter
  1058. -r Interpret pattern as a regular expression pattern
  1059. -s Smart case; like -i unless pattern contains upper case letters
  1060. -t Apply filter and search pattern as you type
  1061. -v Inverts the match
  1062. Multiple flags can be combined. For example, ":scout -gpt" would create
  1063. a :filter-like command using globbing.
  1064. """
  1065. # pylint: disable=bad-whitespace
  1066. AUTO_OPEN = 'a'
  1067. OPEN_ON_ENTER = 'e'
  1068. FILTER = 'f'
  1069. SM_GLOB = 'g'
  1070. IGNORE_CASE = 'i'
  1071. KEEP_OPEN = 'k'
  1072. SM_LETTERSKIP = 'l'
  1073. MARK = 'm'
  1074. UNMARK = 'M'
  1075. PERM_FILTER = 'p'
  1076. SM_REGEX = 'r'
  1077. SMART_CASE = 's'
  1078. AS_YOU_TYPE = 't'
  1079. INVERT = 'v'
  1080. # pylint: enable=bad-whitespace
  1081. def __init__(self, *args, **kwargs):
  1082. super(scout, self).__init__(*args, **kwargs)
  1083. self._regex = None
  1084. self.flags, self.pattern = self.parse_flags()
  1085. def execute(self): # pylint: disable=too-many-branches
  1086. thisdir = self.fm.thisdir
  1087. flags = self.flags
  1088. pattern = self.pattern
  1089. regex = self._build_regex()
  1090. count = self._count(move=True)
  1091. self.fm.thistab.last_search = regex
  1092. self.fm.set_search_method(order="search")
  1093. if (self.MARK in flags or self.UNMARK in flags) and thisdir.files:
  1094. value = flags.find(self.MARK) > flags.find(self.UNMARK)
  1095. if self.FILTER in flags:
  1096. for fobj in thisdir.files:
  1097. thisdir.mark_item(fobj, value)
  1098. else:
  1099. for fobj in thisdir.files:
  1100. if regex.search(fobj.relative_path):
  1101. thisdir.mark_item(fobj, value)
  1102. if self.PERM_FILTER in flags:
  1103. thisdir.filter = regex if pattern else None
  1104. # clean up:
  1105. self.cancel()
  1106. if self.OPEN_ON_ENTER in flags or \
  1107. (self.AUTO_OPEN in flags and count == 1):
  1108. if pattern == '..':
  1109. self.fm.cd(pattern)
  1110. else:
  1111. self.fm.move(right=1)
  1112. if self.quickly_executed:
  1113. self.fm.block_input(0.5)
  1114. if self.KEEP_OPEN in flags and thisdir != self.fm.thisdir:
  1115. # reopen the console:
  1116. if not pattern:
  1117. self.fm.open_console(self.line)
  1118. else:
  1119. self.fm.open_console(self.line[0:-len(pattern)])
  1120. if self.quickly_executed and thisdir != self.fm.thisdir and pattern != "..":
  1121. self.fm.block_input(0.5)
  1122. def cancel(self):
  1123. self.fm.thisdir.temporary_filter = None
  1124. self.fm.thisdir.refilter()
  1125. def quick(self):
  1126. asyoutype = self.AS_YOU_TYPE in self.flags
  1127. if self.FILTER in self.flags:
  1128. self.fm.thisdir.temporary_filter = self._build_regex()
  1129. if self.PERM_FILTER in self.flags and asyoutype:
  1130. self.fm.thisdir.filter = self._build_regex()
  1131. if self.FILTER in self.flags or self.PERM_FILTER in self.flags:
  1132. self.fm.thisdir.refilter()
  1133. if self._count(move=asyoutype) == 1 and self.AUTO_OPEN in self.flags:
  1134. return True
  1135. return False
  1136. def tab(self, tabnum):
  1137. self._count(move=True, offset=tabnum)
  1138. def _build_regex(self):
  1139. if self._regex is not None:
  1140. return self._regex
  1141. frmat = "%s"
  1142. flags = self.flags
  1143. pattern = self.pattern
  1144. if pattern == ".":
  1145. return re.compile("")
  1146. # Handle carets at start and dollar signs at end separately
  1147. if pattern.startswith('^'):
  1148. pattern = pattern[1:]
  1149. frmat = "^" + frmat
  1150. if pattern.endswith('$'):
  1151. pattern = pattern[:-1]
  1152. frmat += "$"
  1153. # Apply one of the search methods
  1154. if self.SM_REGEX in flags:
  1155. regex = pattern
  1156. elif self.SM_GLOB in flags:
  1157. regex = re.escape(pattern).replace("\\*", ".*").replace("\\?", ".")
  1158. elif self.SM_LETTERSKIP in flags:
  1159. regex = ".*".join(re.escape(c) for c in pattern)
  1160. else:
  1161. regex = re.escape(pattern)
  1162. regex = frmat % regex
  1163. # Invert regular expression if necessary
  1164. if self.INVERT in flags:
  1165. regex = "^(?:(?!%s).)*$" % regex
  1166. # Compile Regular Expression
  1167. # pylint: disable=no-member
  1168. options = re.UNICODE
  1169. if self.IGNORE_CASE in flags or self.SMART_CASE in flags and \
  1170. pattern.islower():
  1171. options |= re.IGNORECASE
  1172. # pylint: enable=no-member
  1173. try:
  1174. self._regex = re.compile(regex, options)
  1175. except re.error:
  1176. self._regex = re.compile("")
  1177. return self._regex
  1178. def _count(self, move=False, offset=0):
  1179. count = 0
  1180. cwd = self.fm.thisdir
  1181. pattern = self.pattern
  1182. if not pattern or not cwd.files:
  1183. return 0
  1184. if pattern == '.':
  1185. return 0
  1186. if pattern == '..':
  1187. return 1
  1188. deq = deque(cwd.files)
  1189. deq.rotate(-cwd.pointer - offset)
  1190. i = offset
  1191. regex = self._build_regex()
  1192. for fsobj in deq:
  1193. if regex.search(fsobj.relative_path):
  1194. count += 1
  1195. if move and count == 1:
  1196. cwd.move(to=(cwd.pointer + i) % len(cwd.files))
  1197. self.fm.thisfile = cwd.pointed_obj
  1198. if count > 1:
  1199. return count
  1200. i += 1
  1201. return count == 1
  1202. class narrow(Command):
  1203. """
  1204. :narrow
  1205. Show only the files selected right now. If no files are selected,
  1206. disable narrowing.
  1207. """
  1208. def execute(self):
  1209. if self.fm.thisdir.marked_items:
  1210. selection = [f.basename for f in self.fm.thistab.get_selection()]
  1211. self.fm.thisdir.narrow_filter = selection
  1212. else:
  1213. self.fm.thisdir.narrow_filter = None
  1214. self.fm.thisdir.refilter()
  1215. class filter_inode_type(Command):
  1216. """
  1217. :filter_inode_type [dfl]
  1218. Displays only the files of specified inode type. Parameters
  1219. can be combined.
  1220. d display directories
  1221. f display files
  1222. l display links
  1223. """
  1224. def execute(self):
  1225. if not self.arg(1):
  1226. self.fm.thisdir.inode_type_filter = ""
  1227. else:
  1228. self.fm.thisdir.inode_type_filter = self.arg(1)
  1229. self.fm.thisdir.refilter()
  1230. class filter_stack(Command):
  1231. """
  1232. :filter_stack ...
  1233. Manages the filter stack.
  1234. filter_stack add FILTER_TYPE ARGS...
  1235. filter_stack pop
  1236. filter_stack decompose
  1237. filter_stack rotate [N=1]
  1238. filter_stack clear
  1239. filter_stack show
  1240. """
  1241. def execute(self):
  1242. from ranger.core.filter_stack import SIMPLE_FILTERS, FILTER_COMBINATORS
  1243. subcommand = self.arg(1)
  1244. if subcommand == "add":
  1245. try:
  1246. self.fm.thisdir.filter_stack.append(
  1247. SIMPLE_FILTERS[self.arg(2)](self.rest(3))
  1248. )
  1249. except KeyError:
  1250. FILTER_COMBINATORS[self.arg(2)](self.fm.thisdir.filter_stack)
  1251. elif subcommand == "pop":
  1252. self.fm.thisdir.filter_stack.pop()
  1253. elif subcommand == "decompose":
  1254. inner_filters = self.fm.thisdir.filter_stack.pop().decompose()
  1255. if inner_filters:
  1256. self.fm.thisdir.filter_stack.extend(inner_filters)
  1257. elif subcommand == "clear":
  1258. self.fm.thisdir.filter_stack = []
  1259. elif subcommand == "rotate":
  1260. rotate_by = int(self.arg(2) or 1)
  1261. self.fm.thisdir.filter_stack = (
  1262. self.fm.thisdir.filter_stack[-rotate_by:]
  1263. + self.fm.thisdir.filter_stack[:-rotate_by]
  1264. )
  1265. elif subcommand == "show":
  1266. stack = list(map(str, self.fm.thisdir.filter_stack))
  1267. pager = self.fm.ui.open_pager()
  1268. pager.set_source(["Filter stack: "] + stack)
  1269. pager.move(to=100, percentage=True)
  1270. return
  1271. else:
  1272. self.fm.notify(
  1273. "Unknown subcommand: {}".format(subcommand),
  1274. bad=True
  1275. )
  1276. return
  1277. self.fm.thisdir.refilter()
  1278. class grep(Command):
  1279. """:grep <string>
  1280. Looks for a string in all marked files or directories
  1281. """
  1282. def execute(self):
  1283. if self.rest(1):
  1284. action = ['grep', '--line-number']
  1285. action.extend(['-e', self.rest(1), '-r'])
  1286. action.extend(f.path for f in self.fm.thistab.get_selection())
  1287. self.fm.execute_command(action, flags='p')
  1288. class flat(Command):
  1289. """
  1290. :flat <level>
  1291. Flattens the directory view up to the specified level.
  1292. -1 fully flattened
  1293. 0 remove flattened view
  1294. """
  1295. def execute(self):
  1296. try:
  1297. level_str = self.rest(1)
  1298. level = int(level_str)
  1299. except ValueError:
  1300. level = self.quantifier
  1301. if level is None:
  1302. self.fm.notify("Syntax: flat <level>", bad=True)
  1303. return
  1304. if level < -1:
  1305. self.fm.notify("Need an integer number (-1, 0, 1, ...)", bad=True)
  1306. self.fm.thisdir.unload()
  1307. self.fm.thisdir.flat = level
  1308. self.fm.thisdir.load_content()
  1309. # Version control commands
  1310. # --------------------------------
  1311. class stage(Command):
  1312. """
  1313. :stage
  1314. Stage selected files for the corresponding version control system
  1315. """
  1316. def execute(self):
  1317. from ranger.ext.vcs import VcsError
  1318. if self.fm.thisdir.vcs and self.fm.thisdir.vcs.track:
  1319. filelist = [f.path for f in self.fm.thistab.get_selection()]
  1320. try:
  1321. self.fm.thisdir.vcs.action_add(filelist)
  1322. except VcsError as ex:
  1323. self.fm.notify('Unable to stage files: {0}'.format(ex))
  1324. self.fm.ui.vcsthread.process(self.fm.thisdir)
  1325. else:
  1326. self.fm.notify('Unable to stage files: Not in repository')
  1327. class unstage(Command):
  1328. """
  1329. :unstage
  1330. Unstage selected files for the corresponding version control system
  1331. """
  1332. def execute(self):
  1333. from ranger.ext.vcs import VcsError
  1334. if self.fm.thisdir.vcs and self.fm.thisdir.vcs.track:
  1335. filelist = [f.path for f in self.fm.thistab.get_selection()]
  1336. try:
  1337. self.fm.thisdir.vcs.action_reset(filelist)
  1338. except VcsError as ex:
  1339. self.fm.notify('Unable to unstage files: {0}'.format(ex))
  1340. self.fm.ui.vcsthread.process(self.fm.thisdir)
  1341. else:
  1342. self.fm.notify('Unable to unstage files: Not in repository')
  1343. # Metadata commands
  1344. # --------------------------------
  1345. class prompt_metadata(Command):
  1346. """
  1347. :prompt_metadata <key1> [<key2> [<key3> ...]]
  1348. Prompt the user to input metadata for multiple keys in a row.
  1349. """
  1350. _command_name = "meta"
  1351. _console_chain = None
  1352. def execute(self):
  1353. prompt_metadata._console_chain = self.args[1:]
  1354. self._process_command_stack()
  1355. def _process_command_stack(self):
  1356. if prompt_metadata._console_chain:
  1357. key = prompt_metadata._console_chain.pop()
  1358. self._fill_console(key)
  1359. else:
  1360. for col in self.fm.ui.browser.columns:
  1361. col.need_redraw = True
  1362. def _fill_console(self, key):
  1363. metadata = self.fm.metadata.get_metadata(self.fm.thisfile.path)
  1364. if key in metadata and metadata[key]:
  1365. existing_value = metadata[key]
  1366. else:
  1367. existing_value = ""
  1368. text = "%s %s %s" % (self._command_name, key, existing_value)
  1369. self.fm.open_console(text, position=len(text))
  1370. class meta(prompt_metadata):
  1371. """
  1372. :meta <key> [<value>]
  1373. Change metadata of a file. Deletes the key if value is empty.
  1374. """
  1375. def execute(self):
  1376. key = self.arg(1)
  1377. update_dict = dict()
  1378. update_dict[key] = self.rest(2)
  1379. selection = self.fm.thistab.get_selection()
  1380. for fobj in selection:
  1381. self.fm.metadata.set_metadata(fobj.path, update_dict)
  1382. self._process_command_stack()
  1383. def tab(self, tabnum):
  1384. key = self.arg(1)
  1385. metadata = self.fm.metadata.get_metadata(self.fm.thisfile.path)
  1386. if key in metadata and metadata[key]:
  1387. return [" ".join([self.arg(0), self.arg(1), metadata[key]])]
  1388. return [self.arg(0) + " " + k for k in sorted(metadata)
  1389. if k.startswith(self.arg(1))]
  1390. class linemode(default_linemode):
  1391. """
  1392. :linemode <mode>
  1393. Change what is displayed as a filename.
  1394. - "mode" may be any of the defined linemodes (see: ranger.core.linemode).
  1395. "normal" is mapped to "filename".
  1396. """
  1397. def execute(self):
  1398. mode = self.arg(1)
  1399. if mode == "normal":
  1400. from ranger.core.linemode import DEFAULT_LINEMODE
  1401. mode = DEFAULT_LINEMODE
  1402. if mode not in self.fm.thisfile.linemode_dict:
  1403. self.fm.notify("Unhandled linemode: `%s'" % mode, bad=True)
  1404. return
  1405. self.fm.thisdir.set_linemode_of_children(mode)
  1406. # Ask the browsercolumns to redraw
  1407. for col in self.fm.ui.browser.columns:
  1408. col.need_redraw = True
  1409. class yank(Command):
  1410. """:yank [name|dir|path]
  1411. Copies the file's name (default), directory or path into both the primary X
  1412. selection and the clipboard.
  1413. """
  1414. modes = {
  1415. '': 'basename',
  1416. 'name_without_extension': 'basename_without_extension',
  1417. 'name': 'basename',
  1418. 'dir': 'dirname',
  1419. 'path': 'path',
  1420. }
  1421. def execute(self):
  1422. import subprocess
  1423. def clipboards():
  1424. from ranger.ext.get_executables import get_executables
  1425. clipboard_managers = {
  1426. 'xclip': [
  1427. ['xclip'],
  1428. ['xclip', '-selection', 'clipboard'],
  1429. ],
  1430. 'xsel': [
  1431. ['xsel'],
  1432. ['xsel', '-b'],
  1433. ],
  1434. 'pbcopy': [
  1435. ['pbcopy'],
  1436. ],
  1437. }
  1438. ordered_managers = ['pbcopy', 'xclip', 'xsel']
  1439. executables = get_executables()
  1440. for manager in ordered_managers:
  1441. if manager in executables:
  1442. return clipboard_managers[manager]
  1443. return []
  1444. clipboard_commands = clipboards()
  1445. mode = self.modes[self.arg(1)]
  1446. selection = self.get_selection_attr(mode)
  1447. new_clipboard_contents = "\n".join(selection)
  1448. for command in clipboard_commands:
  1449. process = subprocess.Popen(command, universal_newlines=True,
  1450. stdin=subprocess.PIPE)
  1451. process.communicate(input=new_clipboard_contents)
  1452. def get_selection_attr(self, attr):
  1453. return [getattr(item, attr) for item in
  1454. self.fm.thistab.get_selection()]
  1455. def tab(self, tabnum):
  1456. return (
  1457. self.start(1) + mode for mode
  1458. in sorted(self.modes.keys())
  1459. if mode
  1460. )