Dotfiles for my tiling window manager + terminal workflow.
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.

1769 lines
53 KiB

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