[
  {
    "path": ".gitignore",
    "content": "doc/tags\n*.pyc\n"
  },
  {
    "path": "README.md",
    "content": "LLDB Vim Frontend (UNMAINTAINED)\n=================\n\nThis plugin provides lldb debbuging integration including\n\n    * breakpoints\n    * watchpoints\n    * threads view\n    * locals view\n    * and more ...\n\nArbitrary valid lldb commands can be invoked as well.\n\n**NOTE** : This is a fork of the plugin which is part of the llvm distribution. The original\ncan be found at http://llvm.org/svn/llvm-project/lldb/trunk/utils/vim-lldb/.\n\n![](https://raw.github.com/gilligan/vim-lldb/master/vim-lldb.png)\n\nPrerequisites\n-------------\n\n* vim >= 7.3 on Linux or OSX with python support built in\n* lldb executable needs to be in the path\n\nInstallation\n------------\n\nInstallation is easiest using a package manager such as bundle:\n\n    Bundle \"gilligan/vim-lldb\"\n\nOf course you are free to manually copy the files to your vimrc folder if you prefer that for\nwhatever weird reason.\n\n\nUsage/Getting Help\n------------------\n\nPlease refer to the vim help for a short 'getting started' section and\ninformation on the available commands and configuration options. (:he lldb).\n"
  },
  {
    "path": "doc/lldb.txt",
    "content": "*lldb.txt* A plugin that enables debugging from your favourite editor\n\n                        _                 ____    ____\n                 _   __(_)___ ___        / / /___/ / /_\n                | | / / / __ `__ \\______/ / / __  / __ \\\n                | |/ / / / / / / /_____/ / / /_/ / /_/ /\n                |___/_/_/ /_/ /_/     /_/_/\\__,_/_.___/\n\n                   LLDB Debugger Ingegration For VIM\n\n==============================================================================\n\nCONTENTS                                                       *lldb-contents*\n\n    1. Introduction .................... |lldb-intro|\n    2. Getting Started ................. |lldb-start|\n    3. Commands ........................ |lldb-commands|\n    4. Mappings ........................ |lldb-mappings|\n    4. License ......................... |lldb-license|\n    5. Bugs ............................ |lldb-bugs|\n    6. Contributing .................... |lldb-contributing|\n\n\nMaintainer :       Tobias Pflug <tobias.pflug@gmail.com>\nOriginal Author:   Daniel Malea <daniel.malea@intel.com>\nLicense:           Same terms as Vim itself (see |license|)\n\nINTRODUCTION                                    *lldb-intro*\n\nThe plugin provides an interface to the lldb debugger allowing for\nconvenient debugging sessions inside your favorite editor including\nfeatures such as breakpoints, stepping, watchpoints etc.\n\nThe original plugin can be found here:\n\nhttp://llvm.org/svn/llvm-project/lldb/trunk/utils/vim-lldb/\n\nCredit for pretty much all current functionality goes to the original\nauthors. Currently only minor modifications have been made to the\noriginal plugin.\n\n\nGETTING STARTED                                 *lldb-start*\n\nTo quickly get started compile (don't forget to compile with debugging\nsymbols) and start some program. Then open a source file belonging to the\nprogram in vim and execute ':Lattach <program-name>.' Then select some\nline in the source file and execute ':Lbreakpoint' to set a breakpint at\nthe current line.\n\nOnce the program reaches the specified breakpoint you will be able to\ninspect state and step through the proram using the commands described below.\n\nCOMMANDS                                        *lldb-commands*\n\nThe LLDB command interpreter is exposed to Vim's command mode using the\n':L' prefix. Tab-completion is available and will cycle through commands.\nSome commands have modified behaviour in Vim; for example, :Lbreakpoint\nwith no arguments will set a breakpoint at the current cursor, rather than\nprinting the standard help information for the LLDB command 'breakpoint'.\n\n                                                *lldb-windows*\n\nIn addition to the standard commands available under the LLDB interpreter,\nthere are also commands to display or hide informational debugger panes.\n\nWindows can be shown or hidden using the ':Lhide <name>' or ':Lshow <name>'\ncommands.\n                                                *lldb-:Lhide*\n:Lhide [windowname]     Hide informational debugger pane named 'windowname'.\n\n                                                *lldb-:Lshow*\n:Lshow [windowname]     Show informational debugger pane named 'windowname'.\n\nPossible window name arguments to the Lhide and Lshow commands include:\n\n    * backtrace\n    * breakpoints\n    * disassembly\n    * locals\n    * registers\n    * threads\n                                                *lldb-:Lattach*\n:Lattach <process-name> Attach to a process by name.\n\n                                                *lldb-:Ldetach*\n:Ldetach                Detach from the current process.\n\n                                                *lldb-:Ltarget*\n:Ltarget [[create] executable]\n                        Create a target with the specified executable. If\n                        run with a single argument, that argument is assumed\n                        to be a path to the executable to be debugged.\n                        Otherwise, all arguments are passed into LLDB's command\n                        interpreter.\n\n                                                *lldb-:Lstart*\n:Lstart                 Create a process by executing the current target\n                        and wait for LLDB to attach.\n\n                                                *lldb-:Lrun*\n:Lrun                   Create a process by executing the current target\n                        without waiting for LLDB to attach.\n\n                                                *lldb-:Lcontinue*\n:Lcontinue              Continue execution of the process until the next\n                        breakpoint is hit or the process exits.\n\n                                                *lldb-:Lthread*\n:Lthread <args>         Passes through to LLDB. See :Lhelp thread.\n\n                                                *lldb-:Lstep*\n:Lstep                  Step into the current function call.\n\n                                                *lldb-:Lstepin*\n:Lstepin                Step into the current function call.\n\n                                                *lldb-:Lstepinst*\n:Lstepinst              Step one instruction.\n\n                                                *lldb-:Lstepinstover*\n:Lstepinstover          Step one instruction, but skip over jump or call\n                        instructions.\n\n                                                *lldb-:Lnext*\n:Lnext                  Step to the next line.\n\n                                                *lldb-:Lfinish*\n:Lfinish                Step out of the current function.\n\n                                                *lldb-:Lbreakpoint*\n:Lbreakpoint [args]     When arguments are provided, the lldb breakpoint\n                        command is invoked. If no arguments are provided,\n                        a breakpoint at the location under the cursor.\n\n                                                *lldb-:Lprint*\n                                                *lldb-:Lpo*\n                                                *lldb-:LpO*\n:Lprint <expr>          Aliases to the lldb print and po commands. Cursor\n:Lpo <expr>             word (cursor WORD for LpO) will be used when\n:LpO <expr>             expression omitted.\n\nMAPPINGS                                        *lldb-mappings*\n\nThere are no default mappings defined by the plugin. All commands described\nabove can be mapped by defining a respective variable:\n\n    let g:lldb_map_Lframe = \"<leader>f\"\n\nThis will map the Lframe command to \"<leader>f\". Other commands can be\nmapped accordingly using 'lldb_map_' + <command name>.\n\n\nLICENSE                                         *lldb-license*\n\nSame as Vim itself.\n\nBUGS                                            *lldb-bugs*\n\nIf you run into a bug use the github issue tracker to report it:\nhttp://github.com/gilligan/vim-lldb/issues/\n\nCONTRIBUTING                                    *lldb-contributing*\n\nIf you want to help out you are more then welcome to do so. In fact\nI am sure there are plenty of people out there that will do a better\njob with this plugin than me. My C skills are more than rusty. I mostly\nwanted to make this nice plugin more public and host it in a way in which\nit is easy to install with your favorite plugin manager.\n\nLong story short: Bring on your forks and pull requests.\n\n vim:tw=78:sw=4:ft=help:norl:\n"
  },
  {
    "path": "plugin/lldb.vim",
    "content": "\" ---------------------------------------------------------------------\n\"  File:        lldb.vim\n\"  Description: LLDB Debugger Integration Plugin\n\"  Maintainer:  Tobias Pflug <tobias.pflug@gmail.com>\n\"  License:     Same License as Vim itself\n\"  --------------------------------------------------------------------\n\nif (exists('g:loaded_lldb') && g:loaded_lldb) || v:version < 703 || &cp || !has('python')\n    finish\nendif\nlet g:loaded_lldb = 1\n\n\"\n\" format of the command entries is as follows:\n\"   [ command name , completion function, nargs, python code, keymap]\n\"\nlet s:lldb_commands = [\n\\ ['Lhide',            's:CompleteWindow',  '1',   'ctrl.doHide(\"<args>\")'],\n\\ ['Lshow',            's:CompleteWindow',  '1',   'ctrl.doShow(\"<args>\")'],\n\\ ['Lstart',           '',                  '*',   'ctrl.doLaunch(True, \"<args>\")'],\n\\ ['Lrun',             '',                  '*',   'ctrl.doLaunch(False, \"<args>\")'],\n\\ ['Lattach',          '',                  '1',   'ctrl.doAttach(\"<args>\")'],\n\\ ['Ldetach',          '',                  '0',   'ctrl.doDetach()'],\n\\ ['Lregexpattach',    's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-attach\", \"<args>\")'],\n\\ ['Lregexpbreak',     's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-break\", \"<args>\")'],\n\\ ['Lregexpbt',        's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-bt\", \"<args>\")'],\n\\ ['Lregexpdown',      's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-down\", \"<args>\")'],\n\\ ['Lregexptbreak',    's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-tbreak\", \"<args>\")'],\n\\ ['Lregexpdisplay',   's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-display\", \"<args>\")'],\n\\ ['Lregexpundisplay', 's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-undisplay\", \"<args>\")'],\n\\ ['Lregexpup',        's:CompleteCommand', '*',   'ctrl.doCommand(\"_regexp-up\", \"<args>\")'],\n\\ ['Lapropos',         's:CompleteCommand', '*',   'ctrl.doCommand(\"apropos\", \"<args>\")'],\n\\ ['Lbacktrace',       's:CompleteCommand', '*',   'ctrl.doCommand(\"bt\", \"<args>\")'],\n\\ ['Lbreakpoint',      's:CompleteCommand', '*',   'ctrl.doBreakpoint(\"<args>\")', '<leader>lb'],\n\\ [\"Lcommand\",         \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"command\", \"<args>\")'],\n\\ [\"Ldisassemble\",     \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"disassemble\", \"<args>\")'],\n\\ [\"Lexpression\",      \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"expression\", \"<args>\")'],\n\\ [\"Lhelp\",            \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"help\", \"<args>\")'],\n\\ [\"Llog\",             \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"log\", \"<args>\")'],\n\\ [\"Lplatform\",        \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"platform\",\"<args>\")'],\n\\ [\"Lplugin\",          \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"plugin\", \"<args>\")'],\n\\ [\"Lprocess\",         \"s:CompleteCommand\", \"*\",   'ctrl.doProcess(\"<args>\")'],\n\\ [\"Lregister\",        \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"register\", \"<args>\")'],\n\\ [\"Lscript\",          \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"script\", \"<args>\")'],\n\\ [\"Lsettings\",        \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"settings\",\"<args>\")'],\n\\ [\"Lsource\",          \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"source\", \"<args>\")'],\n\\ [\"Ltype\",            \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"type\", \"<args>\")'],\n\\ [\"Lversion\",         \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"version\", \"<args>\")'],\n\\ [\"Lwatchpoint\",      \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"watchpoint\", \"<args>\")'],\n\\ [\"Lprint\",           \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"print\", vim.eval(\"s:CursorWord(\"<args>\")\"))'],\n\\ [\"Lpo\",              \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"po\", vim.eval(\"s:CursorWord(\"<args>\")\"))'],\n\\ [\"LpO\",              \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"po\", vim.eval(\"s:CursorWORD(\"<args>\")\"))'],\n\\ [\"Lbt\",              \"s:CompleteCommand\", \"*\",   'ctrl.doCommand(\"bt\", \"<args>\")'],\n\\ [\"Lframe\",           \"s:CompleteCommand\", \"*\",   'ctrl.doSelect(\"frame\", \"<args>\")'],\n\\ [\"Lup\",              \"s:CompleteCommand\", \"?\",   'ctrl.doCommand(\"up\", \"<args>\", print_on_success=False, goto_file=True)'],\n\\ [\"Ldown\",            \"s:CompleteCommand\", \"?\",   'ctrl.doCommand(\"down\", \"<args>\", print_on_success=False, goto_file=True)'],\n\\ [\"Lthread\",          \"s:CompleteCommand\", \"*\",   'ctrl.doSelect(\"thread\", \"<args>\")'],\n\\ [\"Ltarget\",          \"s:CompleteCommand\", \"*\",   'ctrl.doTarget(\"<args>\")'],\n\\ ['Lcontinue',        \"s:CompleteCommand\", \"*\",   'ctrl.doContinue()', '<leader>lc'],\n\\ ['Lstepinst',        \"\",                  \"0\",   'ctrl.doStep(StepType.INSTRUCTION)'],\n\\ ['Lstepinstover',    \"\",                  \"0\",   'ctrl.doStep(StepType.INSTRUCTION_OVER)'],\n\\ ['Lstepin',          \"\",                  \"0\",   'ctrl.doStep(StepType.INTO)'],\n\\ ['Lstep',            \"\",                  \"0\",   'ctrl.doStep(StepType.INTO)', '<leader>li'],\n\\ ['Lnext',            \"\",                  \"0\",   'ctrl.doStep(StepType.OVER)', '<leader>ln'],\n\\ ['Lfinish',          \"\",                  \"0\",   'ctrl.doStep(StepType.OUT)'],\n\\ ['Lrefresh',         \"\",                  \"0\",   'ctrl.doRefresh()', '<leader>lr']\n\\]\n\n\" Python module init {{{\nfunction! lldb#pythonInit()\n    execute 'python import sys'\n    let python_module_dir = fnameescape(globpath(&runtimepath, 'python-vim-lldb'))\n    execute 'python sys.path.append(\"' . python_module_dir . '\")'\n    execute 'pyfile ' . python_module_dir . '/plugin.py'\nendfunction\n\" }}}\n\n\n\" Command registration {{{\nfunction! lldb#createCommands()\n    for cmd in s:lldb_commands\n        let complFun = ''\n        let nargs = ''\n        if len(cmd[1]) > 0\n            let complFun = '-complete=custom,' . cmd[1]\n        endif\n        if len(cmd[2]) > 0\n            let nargs = '-nargs=' . cmd[2]\n        endif\n        execute 'command ' . complFun . ' ' . nargs . ' ' . cmd[0] . ' python ' . cmd[3]\n    endfor\n    \" hack: service the LLDB event-queue when the cursor moves\n    autocmd CursorMoved * :Lrefresh\n    autocmd CursorHold  * :Lrefresh\n    autocmd VimLeavePre * python ctrl.doExit()\nendfunction\n\"\n\nfunction lldb#createKeyMaps()\n    for cmd in s:lldb_commands\n        \" only map what has been configured by the user\n        if exists('g:lldb_map_' . cmd[0])\n            execute 'nnoremap ' . eval('g:lldb_map_' . cmd[0]) . ' :' . cmd[0] . '<CR>'\n        endif\n    endfor\nendfunction\n\nfunction! s:InitLldbPlugin()\n    call lldb#pythonInit()\n    call lldb#createCommands()\n    call lldb#createKeyMaps()\nendfunction()\n\" }}}\n\n\n\" Command Completion Functions {{{\nfunction! s:CompleteCommand(A, L, P)\n    python << EOF\na = vim.eval(\"a:A\")\nl = vim.eval(\"a:L\")\np = vim.eval(\"a:P\")\nreturnCompleteCommand(a, l, p)\nEOF\nendfunction()\n\nfunction! s:CompleteWindow(A, L, P)\n    python << EOF\na = vim.eval(\"a:A\")\nl = vim.eval(\"a:L\")\np = vim.eval(\"a:P\")\nreturnCompleteWindow(a, l, p)\nEOF\nendfunction()\n\n\" Returns cword if search term is empty\nfunction! s:CursorWord(term)\n    return empty(a:term) ? expand('<cword>') : a:term\nendfunction()\n\n\" Returns cleaned cWORD if search term is empty\nfunction! s:CursorWORD(term)\n    \" Will strip all non-alphabetic characters from both sides\n    return empty(a:term) ?  substitute(expand('<cWORD>'), '^\\A*\\(.\\{-}\\)\\A*$', '\\1', '') : a:term\nendfunction()\n\" }}}\n\n\ncall s:InitLldbPlugin()\n\n"
  },
  {
    "path": "python-vim-lldb/import_lldb.py",
    "content": "\n# Locate and load the lldb python module\n\nimport os, sys\n\ndef import_lldb():\n  \"\"\" Find and import the lldb modules. This function tries to find the lldb module by:\n      1. Simply by doing \"import lldb\" in case the system python installation is aware of lldb. If that fails,\n      2. Executes the lldb executable pointed to by the LLDB environment variable (or if unset, the first lldb\n         on PATH\") with the -P flag to determine the PYTHONPATH to set. If the lldb executable returns a valid\n         path, it is added to sys.path and the import is attempted again. If that fails, 3. On Mac OS X the\n         default Xcode 4.5 installation path.\n  \"\"\"\n\n  # Try simple 'import lldb', in case of a system-wide install or a pre-configured PYTHONPATH\n  try:\n    import lldb\n    return True\n  except ImportError:\n    pass\n\n  # Allow overriding default path to lldb executable with the LLDB environment variable\n  lldb_executable = 'lldb'\n  if 'LLDB' in os.environ and os.path.exists(os.environ['LLDB']):\n    lldb_executable = os.environ['LLDB']\n\n  # Try using builtin module location support ('lldb -P')\n  from subprocess import check_output, CalledProcessError\n  try:\n    with open(os.devnull, 'w') as fnull:\n      lldb_minus_p_path = check_output(\"%s -P\" % lldb_executable, shell=True, stderr=fnull).strip()\n    if not os.path.exists(lldb_minus_p_path):\n      #lldb -P returned invalid path, probably too old\n      pass\n    else:\n      sys.path.append(lldb_minus_p_path)\n      import lldb\n      return True\n  except CalledProcessError:\n    # Cannot run 'lldb -P' to determine location of lldb python module\n    pass\n  except ImportError:\n    # Unable to import lldb module from path returned by `lldb -P`\n    pass\n\n  # On Mac OS X, use the try the default path to XCode lldb module\n  if \"darwin\" in sys.platform:\n    xcode_python_path = \"/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Versions/Current/Resources/Python/\"\n    sys.path.append(xcode_python_path)\n    try:\n      import lldb\n      return True\n    except ImportError:\n      # Unable to import lldb module from default Xcode python path\n      pass\n\n  return False\n\nif not import_lldb():\n  import vim\n  vim.command('redraw | echo \"%s\"' % \" Error loading lldb module; vim-lldb will be disabled. Check LLDB installation or set LLDB environment variable.\")\n"
  },
  {
    "path": "python-vim-lldb/lldb_controller.py",
    "content": "\n#\n# This file defines the layer that talks to lldb\n#\n\nimport os, re, sys\nimport lldb\nimport vim\nfrom vim_ui import UI\n\n# =================================================\n# Convert some enum value to its string counterpart\n# =================================================\n\n# Shamelessly copy/pasted from lldbutil.py in the test suite\ndef state_type_to_str(enum):\n  \"\"\"Returns the stateType string given an enum.\"\"\"\n  if enum == lldb.eStateInvalid:\n    return \"invalid\"\n  elif enum == lldb.eStateUnloaded:\n    return \"unloaded\"\n  elif enum == lldb.eStateConnected:\n    return \"connected\"\n  elif enum == lldb.eStateAttaching:\n    return \"attaching\"\n  elif enum == lldb.eStateLaunching:\n    return \"launching\"\n  elif enum == lldb.eStateStopped:\n    return \"stopped\"\n  elif enum == lldb.eStateRunning:\n    return \"running\"\n  elif enum == lldb.eStateStepping:\n    return \"stepping\"\n  elif enum == lldb.eStateCrashed:\n    return \"crashed\"\n  elif enum == lldb.eStateDetached:\n    return \"detached\"\n  elif enum == lldb.eStateExited:\n    return \"exited\"\n  elif enum == lldb.eStateSuspended:\n    return \"suspended\"\n  else:\n    raise Exception(\"Unknown StateType enum\")\n\nclass StepType:\n  INSTRUCTION = 1\n  INSTRUCTION_OVER = 2\n  INTO = 3\n  OVER = 4\n  OUT = 5\n\nclass LLDBController(object):\n  \"\"\" Handles Vim and LLDB events such as commands and lldb events. \"\"\"\n\n  # Timeouts (sec) for waiting on new events. Because vim is not multi-threaded, we are restricted to\n  # servicing LLDB events from the main UI thread. Usually, we only process events that are already\n  # sitting on the queue. But in some situations (when we are expecting an event as a result of some\n  # user interaction) we want to wait for it. The constants below set these wait period in which the\n  # Vim UI is \"blocked\". Lower numbers will make Vim more responsive, but LLDB will be delayed and higher\n  # numbers will mean that LLDB events are processed faster, but the Vim UI may appear less responsive at\n  # times.\n  eventDelayStep = 2\n  eventDelayLaunch = 1\n  eventDelayContinue = 1\n\n  def __init__(self):\n    \"\"\" Creates the LLDB SBDebugger object and initializes the UI class. \"\"\"\n    self.target = None\n    self.process = None\n    self.load_dependent_modules = True\n\n    self.dbg = lldb.SBDebugger.Create()\n    self.commandInterpreter = self.dbg.GetCommandInterpreter()\n    self.commandInterpreter.HandleCommand(\"settings set target.load-script-from-symbol-file false\", lldb.SBCommandReturnObject())\n\n    self.ui = UI()\n\n  def completeCommand(self, a, l, p):\n    \"\"\" Returns a list of viable completions for command a with length l and cursor at p  \"\"\"\n\n    assert l[0] == 'L'\n    # Remove first 'L' character that all commands start with\n    l = l[1:]\n\n    # Adjust length as string has 1 less character\n    p = int(p) - 1\n\n    result = lldb.SBStringList()\n    num = self.commandInterpreter.HandleCompletion(l, p, 1, -1, result)\n\n    if num == -1:\n      # FIXME: insert completion character... what's a completion character?\n      pass\n    elif num == -2:\n      # FIXME: replace line with result.GetStringAtIndex(0)\n      pass\n\n    if result.GetSize() > 0:\n      results =  filter(None, [result.GetStringAtIndex(x) for x in range(result.GetSize())])\n      return results\n    else:\n      return []\n\n  def doStep(self, stepType):\n    \"\"\" Perform a step command and block the UI for eventDelayStep seconds in order to process\n        events on lldb's event queue.\n        FIXME: if the step does not complete in eventDelayStep seconds, we relinquish control to\n               the main thread to avoid the appearance of a \"hang\". If this happens, the UI will\n               update whenever; usually when the user moves the cursor. This is somewhat annoying.\n    \"\"\"\n    if not self.process:\n      sys.stderr.write(\"No process to step\")\n      return\n    \n    t = self.process.GetSelectedThread()\n    if stepType == StepType.INSTRUCTION:\n      t.StepInstruction(False)\n    if stepType == StepType.INSTRUCTION_OVER:\n      t.StepInstruction(True)\n    elif stepType == StepType.INTO:\n      t.StepInto()\n    elif stepType == StepType.OVER:\n      t.StepOver()\n    elif stepType == StepType.OUT:\n      t.StepOut()\n\n    self.processPendingEvents(self.eventDelayStep, True)\n\n  def doSelect(self, command, args):\n    \"\"\" Like doCommand, but suppress output when \"select\" is the first argument.\"\"\"\n    a = args.split(' ')\n    return self.doCommand(command, args, \"select\" != a[0], True)\n\n  def doProcess(self, args):\n    \"\"\" Handle 'process' command. If 'launch' is requested, use doLaunch() instead\n        of the command interpreter to start the inferior process.\n    \"\"\"\n    a = args.split(' ')\n    if len(args) == 0 or (len(a) > 0 and a[0] != 'launch'):\n      self.doCommand(\"process\", args)\n      #self.ui.update(self.target, \"\", self)\n    else:\n      self.doLaunch('-s' not in args, \"\")\n\n  def doAttach(self, process_name):\n    \"\"\" Handle process attach.  \"\"\"\n    error = lldb.SBError()\n    \n    self.processListener = lldb.SBListener(\"process_event_listener\")\n    self.target = self.dbg.CreateTarget('')\n    self.process = self.target.AttachToProcessWithName(self.processListener, process_name, False, error)\n    if not error.Success():\n      sys.stderr.write(\"Error during attach: \" + str(error))\n      return\n\n    self.ui.activate()\n    self.pid = self.process.GetProcessID()\n\n    print \"Attached to %s (pid=%d)\" % (process_name, self.pid)\n\n  def doDetach(self):\n    if self.process is not None and self.process.IsValid():\n      pid = self.process.GetProcessID()\n      state = state_type_to_str(self.process.GetState())\n      self.process.Detach()\n      self.processPendingEvents(self.eventDelayLaunch)\n\n  def doLaunch(self, stop_at_entry, args):\n    \"\"\" Handle process launch.  \"\"\"\n    error = lldb.SBError()\n\n    fs = self.target.GetExecutable()\n    exe = os.path.join(fs.GetDirectory(), fs.GetFilename())\n    if self.process is not None and self.process.IsValid():\n      pid = self.process.GetProcessID()\n      state = state_type_to_str(self.process.GetState())\n      self.process.Destroy()\n\n    launchInfo = lldb.SBLaunchInfo(args.split(' '))\n    self.process = self.target.Launch(launchInfo, error)\n    if not error.Success():\n      sys.stderr.write(\"Error during launch: \" + str(error))\n      return\n\n    # launch succeeded, store pid and add some event listeners\n    self.pid = self.process.GetProcessID()\n    self.processListener = lldb.SBListener(\"process_event_listener\")\n    self.process.GetBroadcaster().AddListener(self.processListener, lldb.SBProcess.eBroadcastBitStateChanged)\n\n    print \"Launched %s %s (pid=%d)\" % (exe, args, self.pid)\n\n    if not stop_at_entry:\n      self.doContinue()\n    else:\n      self.processPendingEvents(self.eventDelayLaunch)\n\n  def doTarget(self, args):\n    \"\"\" Pass target command to interpreter, except if argument is not one of the valid options, or\n        is create, in which case try to create a target with the argument as the executable. For example:\n          target list        ==> handled by interpreter\n          target create blah ==> custom creation of target 'blah'\n          target blah        ==> also creates target blah\n    \"\"\"\n    target_args = [#\"create\",\n                   \"delete\",\n                   \"list\",\n                   \"modules\",\n                   \"select\",\n                   \"stop-hook\",\n                   \"symbols\",\n                   \"variable\"]\n\n    a = args.split(' ')\n    if len(args) == 0 or (len(a) > 0 and a[0] in target_args):\n      self.doCommand(\"target\", args)\n      return\n    elif len(a) > 1 and a[0] == \"create\":\n      exe = a[1]\n    elif len(a) == 1 and a[0] not in target_args:\n      exe = a[0]\n\n    err = lldb.SBError()\n    self.target = self.dbg.CreateTarget(exe, None, None, self.load_dependent_modules, err)\n    if not self.target:\n      sys.stderr.write(\"Error creating target %s. %s\" % (str(exe), str(err)))\n      return\n\n    self.ui.activate()\n    self.ui.update(self.target, \"created target %s\" % str(exe), self)\n\n  def doContinue(self):\n    \"\"\" Handle 'contiue' command.\n        FIXME: switch to doCommand(\"continue\", ...) to handle -i ignore-count param.\n    \"\"\"\n    if not self.process or not self.process.IsValid():\n      sys.stderr.write(\"No process to continue\")\n      return\n\n    self.process.Continue()\n    self.processPendingEvents(self.eventDelayContinue)\n\n  def doBreakpoint(self, args):\n    \"\"\" Handle breakpoint command with command interpreter, except if the user calls\n        \"breakpoint\" with no other args, in which case add a breakpoint at the line\n        under the cursor.\n    \"\"\"\n    a = args.split(' ')\n    if len(args) == 0:\n      show_output = False\n\n      # User called us with no args, so toggle the bp under cursor\n      cw = vim.current.window\n      cb = vim.current.buffer\n      name = cb.name\n      line = cw.cursor[0]\n\n      # Since the UI is responsbile for placing signs at bp locations, we have to\n      # ask it if there already is one or more breakpoints at (file, line)...\n      if self.ui.haveBreakpoint(name, line):\n        bps = self.ui.getBreakpoints(name, line)\n        args = \"delete %s\" % \" \".join([str(b.GetID()) for b in bps])\n        self.ui.deleteBreakpoints(name, line)\n      else:\n        args = \"set -f %s -l %d\" % (name, line)\n    else:\n      show_output = True\n\n    self.doCommand(\"breakpoint\", args, show_output)\n    return\n\n  def doRefresh(self):\n    \"\"\" process pending events and update UI on request \"\"\"\n    status = self.processPendingEvents()\n\n  def doShow(self, name):\n    \"\"\" handle :Lshow <name> \"\"\"\n    if not name:\n      self.ui.activate()\n      return\n\n    if self.ui.showWindow(name):\n      self.ui.update(self.target, \"\", self)\n\n  def doHide(self, name):\n    \"\"\" handle :Lhide <name> \"\"\"\n    if self.ui.hideWindow(name):\n      self.ui.update(self.target, \"\", self)\n\n  def doExit(self):\n    self.dbg.Terminate()\n    self.dbg = None\n\n  def getCommandResult(self, command, command_args):\n    \"\"\" Run cmd in the command interpreter and returns (success, output) \"\"\"\n    result = lldb.SBCommandReturnObject()\n    cmd = \"%s %s\" % (command, command_args)\n\n    self.commandInterpreter.HandleCommand(cmd, result)\n    return (result.Succeeded(), result.GetOutput() if result.Succeeded() else result.GetError())\n\n  def doCommand(self, command, command_args, print_on_success = True, goto_file=False):\n    \"\"\" Run cmd in interpreter and print result (success or failure) on the vim status line. \"\"\"\n    (success, output) = self.getCommandResult(command, command_args)\n    if success:\n      self.ui.update(self.target, \"\", self, goto_file)\n      if len(output) > 0 and print_on_success:\n        print output\n    else:\n      sys.stderr.write(output)\n\n  def getCommandOutput(self, command, command_args=\"\"):\n    \"\"\" runs cmd in the command interpreter andreturns (status, result) \"\"\"\n    result = lldb.SBCommandReturnObject()\n    cmd = \"%s %s\" % (command, command_args)\n    self.commandInterpreter.HandleCommand(cmd, result)\n    return (result.Succeeded(), result.GetOutput() if result.Succeeded() else result.GetError())\n\n  def processPendingEvents(self, wait_seconds=0, goto_file=True):\n    \"\"\" Handle any events that are queued from the inferior.\n        Blocks for at most wait_seconds, or if wait_seconds == 0,\n        process only events that are already queued.\n    \"\"\"\n\n    status = None\n    num_events_handled = 0\n\n    if self.process is not None:\n      event = lldb.SBEvent()\n      old_state = self.process.GetState()\n      new_state = None\n      done = False\n      if old_state == lldb.eStateInvalid or old_state == lldb.eStateExited:\n        # Early-exit if we are in 'boring' states\n        pass\n      else:\n        while not done and self.processListener is not None:\n          if not self.processListener.PeekAtNextEvent(event):\n            if wait_seconds > 0:\n              # No events on the queue, but we are allowed to wait for wait_seconds\n              # for any events to show up.\n              self.processListener.WaitForEvent(wait_seconds, event)\n              new_state = lldb.SBProcess.GetStateFromEvent(event)\n\n              num_events_handled += 1\n\n            done = not self.processListener.PeekAtNextEvent(event)\n          else:\n            # An event is on the queue, process it here.\n            self.processListener.GetNextEvent(event)\n            new_state = lldb.SBProcess.GetStateFromEvent(event)\n\n            # continue if stopped after attaching\n            if old_state == lldb.eStateAttaching and new_state == lldb.eStateStopped:\n              self.process.Continue()\n\n            # If needed, perform any event-specific behaviour here\n            num_events_handled += 1\n\n    if num_events_handled == 0:\n      pass\n    else:\n      if old_state == new_state:\n        status = \"\"\n      self.ui.update(self.target, status, self, goto_file)\n\n\ndef returnCompleteCommand(a, l, p):\n  \"\"\" Returns a \"\\n\"-separated string with possible completion results\n      for command a with length l and cursor at p.\n  \"\"\"\n  separator = \"\\n\"\n  results = ctrl.completeCommand(a, l, p)\n  vim.command('return \"%s%s\"' % (separator.join(results), separator))\n\ndef returnCompleteWindow(a, l, p):\n  \"\"\" Returns a \"\\n\"-separated string with possible completion results\n      for commands that expect a window name parameter (like hide/show).\n      FIXME: connect to ctrl.ui instead of hardcoding the list here\n  \"\"\"\n  separator = \"\\n\"\n  results = ['breakpoints', 'backtrace', 'disassembly', 'locals', 'threads', 'registers']\n  vim.command('return \"%s%s\"' % (separator.join(results), separator))\n\nglobal ctrl\nctrl = LLDBController()\n"
  },
  {
    "path": "python-vim-lldb/plugin.py",
    "content": "\n# Try to import all dependencies, catch and handle the error gracefully if it fails.\n\nimport import_lldb\n\ntry:\n  import lldb\n  import vim\nexcept ImportError:\n  sys.stderr.write(\"Unable to load vim/lldb module. Check lldb is on the path is available (or LLDB is set) and that script is invoked inside Vim with :pyfile\")\n  pass\nelse:\n  # Everthing went well, so use import to start the plugin controller \n  from lldb_controller import *\n"
  },
  {
    "path": "python-vim-lldb/vim_panes.py",
    "content": "#\n# This file contains implementations of the LLDB display panes in VIM\n#\n# The most generic way to define a new window is to inherit from VimPane\n# and to implement:\n# - get_content() - returns a string with the pane contents\n#\n# Optionally, to highlight text, implement:\n# - get_highlights() - returns a map \n# \n# And call:\n# - define_highlight(unique_name, colour)\n# at some point in the constructor.\n#\n#\n# If the pane shows some key-value data that is in the context of a\n# single frame, inherit from FrameKeyValuePane and implement:\n# - get_frame_content(self, SBFrame frame)\n# \n#\n# If the pane presents some information that can be retrieved with\n# a simple LLDB command while the subprocess is stopped, inherit\n# from StoppedCommandPane and call:\n# - self.setCommand(command, command_args)\n# at some point in the constructor.\n#\n# Optionally, you can implement:\n# - get_selected_line()\n# to highlight a selected line and place the cursor there.\n# \n#\n# FIXME: implement WatchlistPane to displayed watched expressions\n# FIXME: define interface for interactive panes, like catching enter \n#        presses to change selected frame/thread...\n# \n\nimport lldb\nimport vim\n\nimport sys\n\n# ==============================================================\n# Get the description of an lldb object or None if not available\n# ==============================================================\n\n# Shamelessly copy/pasted from lldbutil.py in the test suite\ndef get_description(obj, option=None):\n    \"\"\"Calls lldb_obj.GetDescription() and returns a string, or None.\n\n    For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra\n    option can be passed in to describe the detailed level of description\n    desired:\n        o lldb.eDescriptionLevelBrief\n        o lldb.eDescriptionLevelFull\n        o lldb.eDescriptionLevelVerbose\n    \"\"\"\n    method = getattr(obj, 'GetDescription')\n    if not method:\n        return None\n    tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint)\n    if isinstance(obj, tuple):\n        if option is None:\n            option = lldb.eDescriptionLevelBrief\n\n    stream = lldb.SBStream()\n    if option is None:\n        success = method(stream)\n    else:\n        success = method(stream, option)\n    if not success:\n        return None\n    return stream.GetData()\n \ndef get_selected_thread(target):\n  \"\"\" Returns a tuple with (thread, error) where thread == None if error occurs \"\"\"\n  process = target.GetProcess()\n  if process is None or not process.IsValid():\n    return (None, VimPane.MSG_NO_PROCESS)\n\n  thread = process.GetSelectedThread()\n  if thread is None or not thread.IsValid():\n    return (None, VimPane.MSG_NO_THREADS)\n  return (thread, \"\")\n\ndef get_selected_frame(target):\n  \"\"\" Returns a tuple with (frame, error) where frame == None if error occurs \"\"\"\n  (thread, error) = get_selected_thread(target)\n  if thread is None:\n    return (None, error)\n\n  frame = thread.GetSelectedFrame()\n  if frame is None or not frame.IsValid():\n    return (None, VimPane.MSG_NO_FRAME)\n  return (frame, \"\")\n\ndef _cmd(cmd):\n  vim.command(\"call confirm('%s')\" % cmd)\n  vim.command(cmd)\n\ndef move_cursor(line, col=0):\n  \"\"\" moves cursor to specified line and col \"\"\"\n  cw = vim.current.window\n  if cw.cursor[0] != line:\n    vim.command(\"execute \\\"normal %dgg\\\"\" % line)\n\ndef winnr():\n  \"\"\" Returns currently selected window number \"\"\"\n  return int(vim.eval(\"winnr()\"))\n\ndef bufwinnr(name):\n  \"\"\" Returns window number corresponding with buffer name \"\"\"\n  return int(vim.eval(\"bufwinnr('%s')\" % name))\n\ndef goto_window(nr):\n  \"\"\" go to window number nr\"\"\"\n  if nr != winnr():\n    vim.command(str(nr) + ' wincmd w')\n\ndef goto_next_window():\n  \"\"\" go to next window. \"\"\"\n  vim.command('wincmd w')\n  return (winnr(), vim.current.buffer.name)\n\ndef goto_previous_window():\n  \"\"\" go to previously selected window \"\"\"\n  vim.command(\"execute \\\"normal \\\\<c-w>p\\\"\")\n\ndef have_gui():\n  \"\"\" Returns True if vim is in a gui (Gvim/MacVim), False otherwise. \"\"\"\n  return int(vim.eval(\"has('gui_running')\")) == 1\n\nclass PaneLayout(object):\n  \"\"\" A container for a (vertical) group layout of VimPanes \"\"\"\n\n  def __init__(self):\n    self.panes = {}\n\n  def havePane(self, name):\n    \"\"\" Returns true if name is a registered pane, False otherwise \"\"\"\n    return name in self.panes\n\n  def prepare(self, panes = []):\n    \"\"\" Draw panes on screen. If empty list is provided, show all. \"\"\"\n\n    # If we can't select a window contained in the layout, we are doing a first draw\n    first_draw = not self.selectWindow(True)\n    did_first_draw = False\n\n    # Prepare each registered pane\n    for name in self.panes:\n      if name in panes or len(panes) == 0:\n        if first_draw:\n          # First window in layout will be created with :vsp, and closed later\n          vim.command(\":vsp\")\n          first_draw = False\n          did_first_draw = True\n        self.panes[name].prepare()\n\n    if did_first_draw:\n      # Close the split window\n      vim.command(\":q\")\n\n    self.selectWindow(False)\n\n  def contains(self, bufferName = None):\n    \"\"\" Returns True if window with name bufferName is contained in the layout, False otherwise.\n        If bufferName is None, the currently selected window is checked.\n    \"\"\"\n    if not bufferName:\n      bufferName = vim.current.buffer.name\n\n    for p in self.panes:\n      if bufferName is not None and bufferName.endswith(p):\n        return True\n    return False\n\n  def selectWindow(self, select_contained = True):\n    \"\"\" Selects a window contained in the layout (if select_contained = True) and returns True.\n        If select_contained = False, a window that is not contained is selected. Returns False\n        if no group windows can be selected.\n    \"\"\"\n    if select_contained == self.contains():\n      # Simple case: we are already selected\n      return True\n\n    # Otherwise, switch to next window until we find a contained window, or reach the first window again.\n    first = winnr()\n    (curnum, curname) = goto_next_window()\n\n    while not select_contained == self.contains(curname) and curnum != first:\n      (curnum, curname) = goto_next_window()\n\n    return self.contains(curname) == select_contained\n\n  def hide(self, panes = []):\n    \"\"\" Hide panes specified. If empty list provided, hide all. \"\"\"\n    for name in self.panes:\n      if name in panes or len(panes) == 0:\n        self.panes[name].destroy()\n\n  def registerForUpdates(self, p):\n    self.panes[p.name] = p\n\n  def update(self, target, controller):\n    for name in self.panes:\n      self.panes[name].update(target, controller)\n\n\nclass VimPane(object):\n  \"\"\" A generic base class for a pane that displays stuff \"\"\"\n  CHANGED_VALUE_HIGHLIGHT_NAME_GUI = 'ColorColumn'\n  CHANGED_VALUE_HIGHLIGHT_NAME_TERM = 'lldb_changed'\n  CHANGED_VALUE_HIGHLIGHT_COLOUR_TERM = 'darkred'\n\n  SELECTED_HIGHLIGHT_NAME_GUI = 'Cursor'\n  SELECTED_HIGHLIGHT_NAME_TERM = 'lldb_selected'\n  SELECTED_HIGHLIGHT_COLOUR_TERM = 'darkblue'\n\n  MSG_NO_TARGET = \"Target does not exist.\"\n  MSG_NO_PROCESS = \"Process does not exist.\"\n  MSG_NO_THREADS = \"No valid threads.\"\n  MSG_NO_FRAME = \"No valid frame.\"\n\n  # list of defined highlights, so we avoid re-defining them\n  highlightTypes = []\n\n  def __init__(self, owner, name, open_below=False, height=3):\n    self.owner = owner\n    self.name = name\n    self.buffer = None\n    self.maxHeight = 20\n    self.openBelow = open_below\n    self.height = height\n    self.owner.registerForUpdates(self)\n\n  def isPrepared(self):\n    \"\"\" check window is OK \"\"\"\n    if self.buffer == None or len(dir(self.buffer)) == 0 or bufwinnr(self.name) == -1:\n      return False\n    return True\n\n  def prepare(self, method = 'new'):\n    \"\"\" check window is OK, if not then create \"\"\"\n    if not self.isPrepared():\n      self.create(method)\n\n  def on_create(self):\n    pass\n\n  def destroy(self):\n    \"\"\" destroy window \"\"\"\n    if self.buffer == None or len(dir(self.buffer)) == 0:\n      return\n    vim.command('bdelete ' + self.name)\n\n  def create(self, method):\n    \"\"\" create window \"\"\"\n\n    if method != 'edit':\n      belowcmd = \"below\" if self.openBelow else \"\"\n      vim.command('silent %s %s %s' % (belowcmd, method, self.name))\n    else:\n      vim.command('silent %s %s' % (method, self.name))\n\n    self.window = vim.current.window\n  \n    # Set LLDB pane options\n    vim.command(\"setlocal buftype=nofile\") # Don't try to open a file\n    vim.command(\"setlocal noswapfile\")     # Don't use a swap file\n    vim.command(\"setlocal nonumber\")       # Don't display line numbers\n    #vim.command(\"setlocal nowrap\")         # Don't wrap text\n\n    # Set indentation-based folding up\n    # Based on:\n    # http://vim.wikia.com/wiki/Folding_for_plain_text_files_based_on_indentation\n    vim.command(\"setlocal foldmethod=expr\")\n    vim.command(\"setlocal foldexpr=(getline(v:lnum)=~'^$')?-1:((indent(v:lnum)<indent(v:lnum+1))?('>'.indent(v:lnum+1)):indent(v:lnum))\")\n    vim.command(\"setlocal foldtext=getline(v:foldstart)\")\n    vim.command(\"setlocal fillchars=fold:\\ \")\n\n    # Save some parameters and reference to buffer\n    self.buffer = vim.current.buffer\n    self.width  = int( vim.eval(\"winwidth(0)\")  )\n    self.height = int( vim.eval(\"winheight(0)\") )\n\n    self.on_create()\n    goto_previous_window()\n\n  def update(self, target, controller):\n    \"\"\" updates buffer contents \"\"\"\n    self.target = target\n    if not self.isPrepared():\n      # Window is hidden, or otherwise not ready for an update\n      return\n\n    original_cursor = self.window.cursor\n\n    # Select pane\n    goto_window(bufwinnr(self.name))\n\n    # Clean and update content, and apply any highlights.\n    self.clean()\n\n    if self.write(self.get_content(target, controller)):\n      self.apply_highlights()\n\n      cursor = self.get_selected_line()\n      if cursor is None:\n        # Place the cursor at its original position in the window\n        cursor_line = min(original_cursor[0], len(self.buffer))\n        cursor_col = min(original_cursor[1], len(self.buffer[cursor_line - 1]))\n      else:\n        # Place the cursor at the location requested by a VimPane implementation\n        cursor_line = min(cursor, len(self.buffer))\n        cursor_col = self.window.cursor[1]\n\n      self.window.cursor = (cursor_line, cursor_col)\n\n    goto_previous_window()\n\n  def get_selected_line(self):\n    \"\"\" Returns the line number to move the cursor to, or None to leave\n        it where the user last left it.\n        Subclasses implement this to define custom behaviour.\n    \"\"\"\n    return None\n\n  def apply_highlights(self):\n    \"\"\" Highlights each set of lines in  each highlight group \"\"\"\n    highlights = self.get_highlights()\n    for highlightType in highlights:\n      lines = highlights[highlightType]\n      if len(lines) == 0:\n        continue\n\n      cmd = 'match %s /' % highlightType\n      lines = ['\\%' + '%d' % line + 'l' for line in lines]\n      cmd += '\\\\|'.join(lines)\n      cmd += '/'\n      vim.command(cmd)\n\n  def define_highlight(self, name, colour):\n    \"\"\" Defines highlihght \"\"\"\n    if name in VimPane.highlightTypes:\n      # highlight already defined\n      return\n\n    vim.command(\"highlight %s ctermbg=%s guibg=%s\" % (name, colour, colour))\n    VimPane.highlightTypes.append(name)\n\n  def write(self, msg):\n    \"\"\" replace buffer with msg\"\"\"\n    self.prepare()\n\n    msg = str(msg.encode(\"utf-8\", \"replace\")).split('\\n')\n    try:\n      self.buffer.append(msg)\n      vim.command(\"execute \\\"normal ggdd\\\"\")\n    except vim.error:\n      # cannot update window; happens when vim is exiting.\n      return False\n\n    move_cursor(1, 0)\n    return True\n\n  def clean(self):\n    \"\"\" clean all datas in buffer \"\"\"\n    self.prepare()\n    vim.command(':%d')\n    #self.buffer[:] = None\n\n  def get_content(self, target, controller):\n    \"\"\" subclasses implement this to provide pane content \"\"\"\n    assert(0 and \"pane subclass must implement this\")\n    pass\n\n  def get_highlights(self):\n    \"\"\" Subclasses implement this to provide pane highlights.\n        This function is expected to return a map of:\n          { highlight_name ==> [line_number, ...], ... }\n    \"\"\"\n    return {}\n\n\nclass FrameKeyValuePane(VimPane):\n  def __init__(self, owner, name, open_below):\n    \"\"\" Initialize parent, define member variables, choose which highlight\n        to use based on whether or not we have a gui (MacVim/Gvim).\n    \"\"\"\n\n    VimPane.__init__(self, owner, name, open_below)\n\n    # Map-of-maps key/value history { frame --> { variable_name, variable_value } }\n    self.frameValues = {}\n\n    if have_gui():\n      self.changedHighlight = VimPane.CHANGED_VALUE_HIGHLIGHT_NAME_GUI\n    else:\n      self.changedHighlight = VimPane.CHANGED_VALUE_HIGHLIGHT_NAME_TERM\n      self.define_highlight(VimPane.CHANGED_VALUE_HIGHLIGHT_NAME_TERM,\n                            VimPane.CHANGED_VALUE_HIGHLIGHT_COLOUR_TERM)\n \n  def format_pair(self, key, value, changed = False):\n    \"\"\" Formats a key/value pair. Appends a '*' if changed == True \"\"\"\n    marker = '*' if changed else ' '\n    return \"%s %s = %s\\n\" % (marker, key, value)\n\n  def get_content(self, target, controller):\n    \"\"\" Get content for a frame-aware pane. Also builds the list of lines that\n        need highlighting (i.e. changed values.)\n    \"\"\"\n    if target is None or not target.IsValid():\n      return VimPane.MSG_NO_TARGET\n\n    self.changedLines = []\n\n    (frame, err) = get_selected_frame(target)\n    if frame is None:\n      return err\n\n    output = get_description(frame)\n    lineNum = 1\n\n    # Retrieve the last values displayed for this frame\n    frameId = get_description(frame.GetBlock())\n    if frameId in self.frameValues:\n      frameOldValues = self.frameValues[frameId]\n    else:\n      frameOldValues = {}\n\n    # Read the frame variables\n    vals = self.get_frame_content(frame)\n    for (key, value) in vals:\n      lineNum += 1\n      if len(frameOldValues) == 0 or (key in frameOldValues and frameOldValues[key] == value):\n        output += self.format_pair(key, value)\n      else:\n        output += self.format_pair(key, value, True)\n        self.changedLines.append(lineNum)\n      \n    # Save values as oldValues\n    newValues = {}\n    for (key, value) in vals:\n      newValues[key] = value\n    self.frameValues[frameId] = newValues\n\n    return output\n\n  def get_highlights(self):\n    ret = {}\n    ret[self.changedHighlight] = self.changedLines\n    return ret\n\nclass LocalsPane(FrameKeyValuePane):\n  \"\"\" Pane that displays local variables \"\"\"\n  def __init__(self, owner, name = 'locals'):\n    FrameKeyValuePane.__init__(self, owner, name, open_below=True)\n    \n    # FIXME: allow users to customize display of args/locals/statics/scope\n    self.arguments = True\n    self.show_locals = True\n    self.show_statics = False\n    self.show_in_scope_only = True\n\n  def format_variable(self, var, indent = 0):\n    \"\"\" Returns a list of tuples of strings \"(Type) Name\", \"Value\" for SBValue var\n        and its children\n    \"\"\"\n    MAX_DEPTH = 6\n\n    if indent > MAX_DEPTH:\n      return []\n    else:\n      val = var.GetValue()\n      if val is None:\n        # If the value is too big, SBValue.GetValue() returns None; replace with ...\n        val = \"...\"\n\n      children = []\n      if var.GetNumChildren() > 0:\n        for x in var:\n          children.extend(self.format_variable(x, indent + 1))\n\n      return [(\"%s(%s) %s\" % (' ' * indent, var.GetTypeName(), var.GetName()),\n              \"%s\" % val)] + children\n\n  def get_frame_content(self, frame):\n    \"\"\" Returns list of key-value pairs of local variables in frame \"\"\"\n    vals = frame.GetVariables(self.arguments,\n                                   self.show_locals,\n                                   self.show_statics,\n                                   self.show_in_scope_only)\n\n    out = []\n    for v in [self.format_variable(x) for x in vals]:\n      out.extend(v)\n\n    return out\n\nclass RegistersPane(FrameKeyValuePane):\n  \"\"\" Pane that displays the contents of registers \"\"\"\n  def __init__(self, owner, name = 'registers'):\n    FrameKeyValuePane.__init__(self, owner, name, open_below=True)\n\n  def format_register(self, reg):\n    \"\"\" Returns a tuple of strings (\"name\", \"value\") for SBRegister reg. \"\"\"\n    name = reg.GetName()\n    val = reg.GetValue()\n    if val is None:\n      val = \"...\"\n    return (name, val.strip())\n\n  def get_frame_content(self, frame):\n    \"\"\" Returns a list of key-value pairs (\"name\", \"value\") of registers in frame \"\"\"\n\n    result = []\n    for register_sets in frame.GetRegisters():\n      # hack the register group name into the list of registers...\n      result.append((\" = = %s =\" % register_sets.GetName(), \"\"))\n\n      for reg in register_sets:\n        result.append(self.format_register(reg))\n    return result\n\nclass CommandPane(VimPane):\n  \"\"\" Pane that displays the output of an LLDB command \"\"\"\n  def __init__(self, owner, name, open_below, process_required=True):\n    VimPane.__init__(self, owner, name, open_below)\n    self.process_required = process_required\n\n  def setCommand(self, command, args = \"\"):\n    self.command = command\n    self.args = args\n\n  def get_content(self, target, controller):\n    output = \"\"\n    if not target:\n      output = VimPane.MSG_NO_TARGET\n    elif self.process_required and not target.GetProcess():\n      output = VimPane.MSG_NO_PROCESS\n    else:\n      (success, output) = controller.getCommandOutput(self.command, self.args)\n    return output\n\nclass StoppedCommandPane(CommandPane):\n  \"\"\" Pane that displays the output of an LLDB command when the process is\n      stopped; otherwise displays process status. This class also implements\n      highlighting for a single line (to show a single-line selected entity.)\n  \"\"\"\n  def __init__(self, owner, name, open_below):\n    \"\"\" Initialize parent and define highlight to use for selected line. \"\"\"\n    CommandPane.__init__(self, owner, name, open_below)\n    if have_gui():\n      self.selectedHighlight = VimPane.SELECTED_HIGHLIGHT_NAME_GUI\n    else:\n      self.selectedHighlight = VimPane.SELECTED_HIGHLIGHT_NAME_TERM\n      self.define_highlight(VimPane.SELECTED_HIGHLIGHT_NAME_TERM,\n                            VimPane.SELECTED_HIGHLIGHT_COLOUR_TERM)\n \n  def get_content(self, target, controller):\n    \"\"\" Returns the output of a command that relies on the process being stopped.\n        If the process is not in 'stopped' state, the process status is returned.\n    \"\"\"\n    output = \"\"\n    if not target or not target.IsValid():\n      output = VimPane.MSG_NO_TARGET\n    elif not target.GetProcess() or not target.GetProcess().IsValid():\n      output = VimPane.MSG_NO_PROCESS\n    elif target.GetProcess().GetState() == lldb.eStateStopped:\n      (success, output) = controller.getCommandOutput(self.command, self.args)\n    else:\n      (success, output) = controller.getCommandOutput(\"process\", \"status\")\n    return output\n\n  def get_highlights(self):\n    \"\"\" Highlight the line under the cursor. Users moving the cursor has\n        no effect on the selected line.\n    \"\"\"\n    ret = {}\n    line = self.get_selected_line()\n    if line is not None:\n      ret[self.selectedHighlight] = [line]\n      return ret\n    return ret\n\n  def get_selected_line(self):\n    \"\"\" Subclasses implement this to control where the cursor (and selected highlight)\n        is placed.\n    \"\"\"\n    return None\n\nclass DisassemblyPane(CommandPane):\n  \"\"\" Pane that displays disassembly around PC \"\"\"\n  def __init__(self, owner, name = 'disassembly'):\n    CommandPane.__init__(self, owner, name, open_below=True)\n\n    # FIXME: let users customize the number of instructions to disassemble\n    self.setCommand(\"disassemble\", \"-c %d -p\" % self.maxHeight)\n\nclass ThreadPane(StoppedCommandPane):\n  \"\"\" Pane that displays threads list \"\"\"\n  def __init__(self, owner, name = 'threads'):\n    StoppedCommandPane.__init__(self, owner, name, open_below=False)\n    self.setCommand(\"thread\", \"list\")\n\n# FIXME: the function below assumes threads are listed in sequential order,\n#        which turns out to not be the case. Highlighting of selected thread\n#        will be disabled until this can be fixed. LLDB prints a '*' anyways\n#        beside the selected thread, so this is not too big of a problem.\n#  def get_selected_line(self):\n#    \"\"\" Place the cursor on the line with the selected entity.\n#        Subclasses should override this to customize selection.\n#        Formula: selected_line = selected_thread_id + 1\n#    \"\"\"\n#    (thread, err) = get_selected_thread(self.target)\n#    if thread is None:\n#      return None\n#    else:\n#      return thread.GetIndexID() + 1\n\nclass BacktracePane(StoppedCommandPane):\n  \"\"\" Pane that displays backtrace \"\"\"\n  def __init__(self, owner, name = 'backtrace'):\n    StoppedCommandPane.__init__(self, owner, name, open_below=False)\n    self.setCommand(\"bt\", \"\")\n\n\n  def get_selected_line(self):\n    \"\"\" Returns the line number in the buffer with the selected frame. \n        Formula: selected_line = selected_frame_id + 2\n        FIXME: the above formula hack does not work when the function return\n               value is printed in the bt window; the wrong line is highlighted.\n    \"\"\"\n\n    (frame, err) = get_selected_frame(self.target)\n    if frame is None:\n      return None\n    else:\n      return frame.GetFrameID() + 2\n\nclass BreakpointsPane(CommandPane):\n  def __init__(self, owner, name = 'breakpoints'):\n    super(BreakpointsPane, self).__init__(owner, name, open_below=False, process_required=False)\n    self.setCommand(\"breakpoint\", \"list\")\n"
  },
  {
    "path": "python-vim-lldb/vim_signs.py",
    "content": "\n# Classes responsible for drawing signs in the Vim user interface.\n\nimport vim\n\nclass VimSign(object):\n  SIGN_TEXT_BREAKPOINT_RESOLVED = \"B>\"\n  SIGN_TEXT_BREAKPOINT_UNRESOLVED = \"b>\"\n  SIGN_TEXT_PC = \"->\"\n  SIGN_HIGHLIGHT_COLOUR_PC = 'darkblue'\n\n  # unique sign id (for ':[sign/highlight] define)\n  sign_id = 1\n\n  # unique name id (for ':sign place')\n  name_id = 1\n\n  # Map of {(sign_text, highlight_colour) --> sign_name}\n  defined_signs = {}\n\n  def __init__(self, sign_text, buffer, line_number, highlight_colour=None):\n    \"\"\" Define the sign and highlight (if applicable) and show the sign. \"\"\"\n\n    # Get the sign name, either by defining it, or looking it up in the map of defined signs\n    key = (sign_text, highlight_colour)\n    if not key in VimSign.defined_signs:\n      name = self.define(sign_text, highlight_colour)\n    else:\n      name = VimSign.defined_signs[key]\n    \n    self.show(name, buffer.number, line_number)\n    pass\n\n  def define(self, sign_text, highlight_colour):\n    \"\"\" Defines sign and highlight (if highlight_colour is not None). \"\"\"\n    sign_name = \"sign%d\" % VimSign.name_id\n    if highlight_colour is None:\n      vim.command(\"sign define %s text=%s\" % (sign_name, sign_text))\n    else:\n      self.highlight_name = \"highlight%d\" % VimSign.name_id\n      vim.command(\"highlight %s ctermbg=%s guibg=%s\" % (self.highlight_name,\n                                                        highlight_colour,\n                                                        highlight_colour))\n      vim.command(\"sign define %s text=%s linehl=%s texthl=%s\" % (sign_name,\n                                                                  sign_text,\n                                                                  self.highlight_name,\n                                                                  self.highlight_name))\n    VimSign.defined_signs[(sign_text, highlight_colour)] = sign_name\n    VimSign.name_id += 1\n    return sign_name\n \n\n  def show(self, name, buffer_number, line_number):\n    self.id = VimSign.sign_id\n    VimSign.sign_id += 1\n    vim.command(\"sign place %d name=%s line=%d buffer=%s\" % (self.id, name, line_number, buffer_number))\n    pass\n\n  def hide(self):\n    vim.command(\"sign unplace %d\" % self.id)\n    pass\n\nclass BreakpointSign(VimSign):\n  def __init__(self, buffer, line_number, is_resolved):\n    txt = VimSign.SIGN_TEXT_BREAKPOINT_RESOLVED if is_resolved else VimSign.SIGN_TEXT_BREAKPOINT_UNRESOLVED\n    super(BreakpointSign, self).__init__(txt, buffer, line_number)\n\nclass PCSign(VimSign):\n  def __init__(self, buffer, line_number, is_selected_thread):\n    super(PCSign, self).__init__(VimSign.SIGN_TEXT_PC,\n                                 buffer,\n                                 line_number,\n                                 VimSign.SIGN_HIGHLIGHT_COLOUR_PC if is_selected_thread else None)\n"
  },
  {
    "path": "python-vim-lldb/vim_ui.py",
    "content": "\n# LLDB UI state in the Vim user interface.\n\nimport os, re, sys\nimport lldb\nimport vim\nfrom vim_panes import *\nfrom vim_signs import *\n\ndef is_same_file(a, b):\n  \"\"\" returns true if paths a and b are the same file \"\"\"\n  a = os.path.realpath(a)\n  b = os.path.realpath(b)\n  return a in b or b in a\n\nclass UI:\n  def __init__(self):\n    \"\"\" Declare UI state variables \"\"\"\n\n    # Default panes to display\n    self.defaultPanes = ['breakpoints', 'backtrace', 'locals', 'threads', 'registers', 'disassembly']\n\n    # map of tuples (filename, line) --> SBBreakpoint\n    self.markedBreakpoints = {}\n\n    # Currently shown signs\n    self.breakpointSigns = {}\n    self.pcSigns = []\n\n    # Container for panes\n    self.paneCol = PaneLayout()\n\n    # All possible LLDB panes\n    self.backtracePane = BacktracePane(self.paneCol)\n    self.threadPane = ThreadPane(self.paneCol)\n    self.disassemblyPane = DisassemblyPane(self.paneCol)\n    self.localsPane = LocalsPane(self.paneCol)\n    self.registersPane = RegistersPane(self.paneCol)\n    self.breakPane = BreakpointsPane(self.paneCol)\n\n  def activate(self):\n    \"\"\" Activate UI: display default set of panes \"\"\"\n    self.paneCol.prepare(self.defaultPanes)\n\n  def get_user_buffers(self, filter_name=None):\n    \"\"\" Returns a list of buffers that are not a part of the LLDB UI. That is, they\n        are not contained in the PaneLayout object self.paneCol.\n    \"\"\"\n    ret = []\n    for w in vim.windows:\n      b = w.buffer\n      if not self.paneCol.contains(b.name):\n        if filter_name is None or filter_name in b.name:\n          ret.append(b) \n    return ret\n\n  def update_pc(self, process, buffers, goto_file):\n    \"\"\" Place the PC sign on the PC location of each thread's selected frame \"\"\"\n\n    def GetPCSourceLocation(thread):\n      \"\"\" Returns a tuple (thread_index, file, line, column) that represents where\n          the PC sign should be placed for a thread.\n      \"\"\"\n\n      frame = thread.GetSelectedFrame()\n      frame_num = frame.GetFrameID()\n      le = frame.GetLineEntry()\n      while not le.IsValid() and frame_num < thread.GetNumFrames():\n        frame_num += 1\n        le = thread.GetFrameAtIndex(frame_num).GetLineEntry()\n\n      if le.IsValid():\n        path = os.path.join(le.GetFileSpec().GetDirectory(), le.GetFileSpec().GetFilename())\n        return (thread.GetIndexID(), path, le.GetLine(), le.GetColumn())\n      return None\n\n\n    # Clear all existing PC signs\n    del_list = []\n    for sign in self.pcSigns:\n      sign.hide()\n      del_list.append(sign)\n    for sign in del_list:\n      self.pcSigns.remove(sign)\n      del sign\n\n    # Select a user (non-lldb) window \n    if not self.paneCol.selectWindow(False):\n      # No user window found; avoid clobbering by splitting\n      vim.command(\":vsp\")\n\n    # Show a PC marker for each thread\n    for thread in process:\n      loc = GetPCSourceLocation(thread)\n      if not loc:\n        # no valid source locations for PCs. hide all existing PC markers\n        continue\n\n      buf = None\n      (tid, fname, line, col) = loc\n      buffers = self.get_user_buffers(fname)\n      is_selected = thread.GetIndexID() == process.GetSelectedThread().GetIndexID()\n      if len(buffers) == 1:\n        buf = buffers[0]\n        if buf != vim.current.buffer:\n          # Vim has an open buffer to the required file: select it\n          vim.command('execute \":%db\"' % buf.number)\n      elif is_selected and vim.current.buffer.name not in fname and os.path.exists(fname) and goto_file:\n        # FIXME: If current buffer is modified, vim will complain when we try to switch away.\n        #        Find a way to detect if the current buffer is modified, and...warn instead?\n        vim.command('execute \":e %s\"' % fname)\n        buf = vim.current.buffer\n      elif len(buffers) > 1 and goto_file:\n        #FIXME: multiple open buffers match PC location\n        continue\n      else:\n        continue\n\n      self.pcSigns.append(PCSign(buf, line, is_selected))\n\n      if is_selected and goto_file:\n        # if the selected file has a PC marker, move the cursor there too\n        curname = vim.current.buffer.name\n        if curname is not None and is_same_file(curname, fname):\n          move_cursor(line, 0)\n        elif move_cursor:\n          print \"FIXME: not sure where to move cursor because %s != %s \" % (vim.current.buffer.name, fname)\n\n  def update_breakpoints(self, target, buffers):\n    \"\"\" Decorates buffer with signs corresponding to breakpoints in target. \"\"\"\n\n    def GetBreakpointLocations(bp):\n      \"\"\" Returns a list of tuples (resolved, filename, line) where a breakpoint was resolved. \"\"\"\n      if not bp.IsValid():\n        sys.stderr.write(\"breakpoint is invalid, no locations\")\n        return []\n\n      ret = []\n      numLocs = bp.GetNumLocations()\n      for i in range(numLocs):\n        loc = bp.GetLocationAtIndex(i)\n        desc = get_description(loc, lldb.eDescriptionLevelFull)\n        match = re.search('at\\ ([^:]+):([\\d]+)', desc)\n        try:\n          lineNum = int(match.group(2).strip())\n          ret.append((loc.IsResolved(), match.group(1), lineNum))\n        except ValueError as e:\n          sys.stderr.write(\"unable to parse breakpoint location line number: '%s'\" % match.group(2))\n          sys.stderr.write(str(e))\n\n      return ret\n\n\n    if target is None or not target.IsValid():\n      return\n\n    needed_bps = {}\n    for bp_index in range(target.GetNumBreakpoints()):\n      bp = target.GetBreakpointAtIndex(bp_index)\n      locations = GetBreakpointLocations(bp)\n      for (is_resolved, file, line) in GetBreakpointLocations(bp):\n        for buf in buffers:\n          if file in buf.name:\n            needed_bps[(buf, line, is_resolved)] = bp\n\n    # Hide any signs that correspond with disabled breakpoints\n    del_list = []\n    for (b, l, r) in self.breakpointSigns:\n      if (b, l, r) not in needed_bps:\n        self.breakpointSigns[(b, l, r)].hide()\n        del_list.append((b, l, r))\n    for d in del_list:\n      del self.breakpointSigns[d]\n      \n    # Show any signs for new breakpoints\n    for (b, l, r) in needed_bps:\n      bp = needed_bps[(b, l, r)]\n      if self.haveBreakpoint(b.name, l):\n        self.markedBreakpoints[(b.name, l)].append(bp)\n      else:\n        self.markedBreakpoints[(b.name, l)] = [bp]\n\n      if (b, l, r) not in self.breakpointSigns:\n        s = BreakpointSign(b, l, r)\n        self.breakpointSigns[(b, l, r)] = s\n\n  def update(self, target, status, controller, goto_file=False):\n    \"\"\" Updates debugger info panels and breakpoint/pc marks and prints\n        status to the vim status line. If goto_file is True, the user's\n        cursor is moved to the source PC location in the selected frame.\n    \"\"\"\n\n    self.paneCol.update(target, controller)\n    self.update_breakpoints(target, self.get_user_buffers())\n\n    if target is not None and target.IsValid():\n      process = target.GetProcess()\n      if process is not None and process.IsValid():\n        self.update_pc(process, self.get_user_buffers, goto_file)\n\n    if status is not None and len(status) > 0:\n      print status \n\n  def haveBreakpoint(self, file, line):\n    \"\"\" Returns True if we have a breakpoint at file:line, False otherwise  \"\"\"\n    return (file, line) in self.markedBreakpoints\n\n  def getBreakpoints(self, fname, line):\n    \"\"\" Returns the LLDB SBBreakpoint object at fname:line \"\"\"\n    if self.haveBreakpoint(fname, line):\n      return self.markedBreakpoints[(fname, line)]\n    else:\n      return None\n\n  def deleteBreakpoints(self, name, line):\n    del self.markedBreakpoints[(name, line)]\n\n  def showWindow(self, name):\n    \"\"\" Shows (un-hides) window pane specified by name \"\"\"\n    if not self.paneCol.havePane(name):\n      sys.stderr.write(\"unknown window: %s\" % name)\n      return False\n    self.paneCol.prepare([name])\n    return True\n\n  def hideWindow(self, name):\n    \"\"\" Hides window pane specified by name \"\"\"\n    if not self.paneCol.havePane(name):\n      sys.stderr.write(\"unknown window: %s\" % name)\n      return False\n    self.paneCol.hide([name])\n    return True\n\nglobal ui\nui = UI()\n"
  }
]